2013-09-05 34 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 

我希望这可以帮助