2013-09-05 35 views
0

回答學說:QueryBuilder的凡已存在

我能夠做到使用查詢在where子句中不爲空。

/** 
* Finds all developments having at least one image. 
* 
* @param string 
* @return array 
*/ 
public function withImages() 
{ 
    return $this->query->createQueryBuilder('d') 
     ->where('d.images IS NOT EMPTY') 
     ->getQuery() 
     ->getResult(); 
} 

問題

我使用的學說ORM。我希望能夠獲得至少有一個圖像的所有開發,這樣對於查詢中選擇的每個開發,以下屬性都是真實的。 $development->getImages()->count()) > 0

我有一個與圖像實體有一對多關係的開發實體。

/** 
* The Development class provides an abstraction of a development. 
* 
* @Entity 
* @HasLifecycleCallbacks 
* @Table(name="developments") 
**/ 
class Development extends BaseEntitiy { 

    /** @OneToMany(targetEntity="Exquisite\Entity\Image", mappedBy="development") **/ 
    protected $images; 

我有一個DevelopmentRepository,它有一個EntityManager實例和一個實體倉庫實例。我試圖在DevelopmentRepository類的withImages()方法中做到這一點,但沒有多少運氣。

class DevelopmentRepository implements DevelopmentRepositoryInterface { 


    /** 
    * Class Constructor 
    * 
    * @param Doctinre\ORM\EntityManager The EntityManager instance. 
    */ 
    public function __construct(EntityManager $em) 
    { 
     $this->em = $em; 
     $this->query = $this->em->getRepository('Exquisite\Entity\Development'); 
    } 


    /** 
    * Finds all developments having at least one image. 
    * 
    * @param string 
    * @return array 
    */ 
    public function withImages() 
    { 
      $qb = $this->query->createQueryBuilder('d'); 
      $qb2 = $this->em->createQueryBuilder(); 

      return $qb->where($qb->expr()->exists($qb2->select('i.development')->from('Exquisite\Entity\Image', 'i')->getDql())) 
       ->getQuery() 
       ->getResult(); 
    } 

任何幫助,將不勝感激!

回答

1

我有同樣的問題,這對我有效。

我固定只是做了加入(將返回只與項目的訂單):

return $this->createQueryBuilder('so') 
     ->select('so') 
     ->join('so.orderItems', 'soi') 
     ->getQuery() 
     ->getResult(); 

或做一個子查詢與DQL

SELECT so 
FROM Entity\\SalesOrder so 
WHERE (SELECT count(soi.id) FROM Entity\\SalesOrderItem soi WHERE soi.salesOrder = so.id) > 0 

我希望這可以幫助