Adding a Having Clause to Doctrine Statement
doctrine, doctrine-orm, php, sql, symfony
Solution
HAVING clause requires a GROUP BY. In doctrine it would be something like that:
$qb->groupBy('p.id'); // or use an appropriate field
$qb->having('COUNT(*) = :some_count');
$qb->setParameter('some_count', 3);
Assuming you're using mysql, here is a having clause tutorial: http://www.mysqltutorial.org/mysql-having.aspx
Problem
I am new to Doctrine and I am trying to figure out how to add a having clause on my statement. Basically I want to be able to filter down on items returned based on how many attributes the user selects. The code is as follows: ``` // create query builder $qb = $this->getEntityManager()->createQueryBuilder(); $qb->select('p') ->from($this->_entityName, 'p') ->leftJoin('p.options', 'o') ->where('p.active = :active') ->setParameter('active', 1); // add filters $qb->leftJoin('o.attributes', 'a'); $ands = array(); foreach ($value as $id => $values) { echo count($values); $ands[] = $qb->expr()->andX( $qb->expr()->eq('a.attribute_id', intval($id)), $qb->expr()->in('a.attribute_value_id', array_map('intval', $values)) $qb->having('COUNT(*)=3) // THIS DOESN'T WORK //$qb->expr()->having('COUNT(*)=3) // THIS DOESN'T WORK EITHER ); } $where = $qb->expr()->andX(); foreach ($ands as $and) { $where->add($and); } $qb->andWhere($where); $result = $qb->getQuery()->getResult(); return $result; ``` When I try to execute the statement with the having() clause I get this error: Expression of type 'Doctrine\ORM\QueryBuilder' not allowed in this context. Without the having() clause everything works perfectly. I have no idea how to solve this.