在查询中计算一对多的学说

时间:2014-01-16 12:44:38

标签: php symfony orm doctrine-orm doctrine

我有一个实体Shop和Shop有很多InstagramShopPicture,关系如下:

 /**
     * @Exclude()
     * @ORM\OneToMany(targetEntity="InstagramShopPicture", mappedBy="shop", cascade={"persist"})
     * @ORM\OrderBy({"created" = "DESC"})
     */
    protected $userPictures;

我有以下查询,我需要找到有4张或更多图片的商店:

  $query = $em->createQueryBuilder()->select('s')
                  ->from("AppMainBundle:InstagramShop", 's')
                  ->innerJoin('s.userPictures', 'p')
                  ;

      $query->andHaving('COUNT(s.userPictures) >= 4');

为什么这不起作用?什么是正确的方法?

1 个答案:

答案 0 :(得分:1)

Doctrine使用SQL,因此您需要使用GROUP BYHAVING进行SQL操作。

此外,您需要为COUNT指定一个字段,例如p.id,而不是别名。

链接说明HAVINGhttp://www.techonthenet.com/sql/having.php

相关问题