Doctrine实体管理器中的Symfony2子查询

时间:2012-03-08 17:26:03

标签: doctrine symfony entitymanager query-builder

我需要执行此查询:

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

在使用实体管理器的Symfony2中。

我的基本查询构建器是:

 $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();

但我无法弄清楚如何在子查询中添加。

我尝试过单独的查询并加入它:

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

但我明白了:

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

2 个答案:

答案 0 :(得分:8)

一个技巧是构建两个查询,然后使用getDQL()将第一个查询提供给第二个查询。

例如,此查询返回一个不同的游戏ID列表:

    $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));

现在使用dql获取有关游戏本身的其他信息:

    $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()));

有点长的例子,但我不想编辑出来并且可能会破坏它。

答案 1 :(得分:8)

您可以使用DBAL执行任何SQL查询。

$conn = $this->get('database_connection');//create a connection with your DB

$sql="SELECT * FROM (SELECT * FROM product WHERE car =? ORDER BY onSale DESC) AS product_ordered GROUP BY type";   //Your sql Query                
$stmt = $conn->prepare($sql);    // Prepare your sql
$stmt->bindValue(1, 'large');    // bind your values ,if you have to bind another value, you need to write $stmt->bindValue(2, 'anothervalue'); but your order is important so on..
$stmt->execute(); //execute your sql
$result=$stmt->fetchAll(); // fetch your result

快乐编码