adit
adit

Reputation: 33644

doctrine to count one to many in query

I have an entity Shop and Shop has many InstagramShopPicture, the relationship is as follows:

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

I have the following query, and I need to find shops that have 4 or more pictures:

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

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

why doesn't this work? What is the right way to do it?

Upvotes: 0

Views: 1206

Answers (1)

Lumbendil
Lumbendil

Reputation: 2916

Doctrine uses SQL, so you need to do as you'd on SQL, using GROUP BY and HAVING.

Also, you need to specify a field for the COUNT, such as p.id, not an alias.

Link explaining HAVING: http://www.techonthenet.com/sql/having.php

Upvotes: 1

Related Questions