B
B
Bovv2016-02-24 14:03:04
MySQL
Bovv, 2016-02-24 14:03:04

How to properly implement nested queries?

You need to count the number of elements returned in the subquery. If you write the subquery by hand, everything works fine, but if you try to build a query using QueryBuilder, you get an error.
The subquery is written manually:

$qb3 = $this->createQueryBuilder('c')
                   ->select('COUNT(c.id)')
                   ->where('c.id IN (SELECT cl.id FROM Acme\AppBundle\Entity\ClassC cl INNER JOIN Acme\AppBundle\Entity\ClassP p WHERE p.var1 = :var1 AND p.var2 = cl.id GROUP BY cl.id)')
                   ->setParameter('var1', $var);

The subquery is built via QueryBuilder:
$qb = $this->createQueryBuilder('c');
$qb->select('COUNT(c.id)')
      ->where(
          $qb->expr()->in(
              'c.id',
              $this->createQueryBuilder('cl')
                      ->select('cl.id')
                      ->innerJoin('Acme\AppBundle\Entity\ClassP', 'p')
                      ->where('p.var1 = :var1')
                      ->setParameter('var1', $var)
                      ->andWhere('p.var2 = cl.id')
                      ->groupBy('cl.id')
                      ->getDQL()
         )
     );

Both options return exactly the same DQL.
44ba2bd0239945b0831ffdd9fa9d3590.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2016-02-24
@Bovv

Move the parameter initialization for the nested builder to the parent one:
$qb->setParameter('var1', $var)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question