Symfony2 subquery within Doctrine entity manager

BobFlemming picture BobFlemming · Mar 8, 2012 · Viewed 12.8k times · Source

I need to perform this query:

SELECT * FROM (SELECT * FROM product WHERE car = 'large' ORDER BY onSale DESC) AS product_ordered GROUP BY type

In Symfony2 using the entity manager.

My basic query builder would be :

 $query = $em->getRepository('AutomotiveBundle:Car')
        ->createQueryBuilder('p')
        ->where('pr.car = ?1')
        ->andWhere('pr.status = 1')
        ->orderBy('pr.onSale', 'DESC')
        ->setParameter(1, $product->getName())
        ->groupBy('p.type')
        ->getQuery();

But I cannot work out how to add in a subquery to this.

Ive tried making a separate query and joining it like:

 ->andWhere($query->expr()->in('pr.car = ?1',$query2->getQuery()));

But I get:

Call to undefined method Doctrine\ORM\Query::expr()

Answer

Cerad picture Cerad · Mar 8, 2012

One trick is to build two queries and then use getDQL() to feed the first query into the second query.

For example, this query returns a distinct list of game ids:

    $qbGameId = $em->createQueryBuilder();

    $qbGameId->addSelect('distinct gameGameId.id');

    $qbGameId->from('ZaysoCoreBundle:Event','gameGameId');

    $qbGameId->leftJoin('gameGameId.teams','gameTeamGameId');

    if ($date1) $qbGameId->andWhere($qbGameId->expr()->gte('gameGameId.date',$date1));
    if ($date2) $qbGameId->andWhere($qbGameId->expr()->lte('gameGameId.date',$date2));

Now use the dql to get additional information about the games themselves:

    $qbGames = $em->createQueryBuilder();

    $qbGames->addSelect('game');
    $qbGames->addSelect('gameTeam');
    $qbGames->addSelect('team');
    $qbGames->addSelect('field');

    $qbGames->addSelect('gamePerson');
    $qbGames->addSelect('person');

    $qbGames->from('ZaysoCoreBundle:Event','game');

    $qbGames->leftJoin('game.teams',   'gameTeam');
    $qbGames->leftJoin('game.persons', 'gamePerson');
    $qbGames->leftJoin('game.field',   'field');

    $qbGames->leftJoin('gameTeam.team',     'team');
    $qbGames->leftJoin('gamePerson.person', 'person');

    // Here is where we feed in the dql
    $qbGames->andWhere($qbGames->expr()->in('game.id',$qbGameId->getDQL()));

Kind of a long example but i didn't want to edit out stuff and maybe break it.