6

我需要执行此查询:

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()
4

2 回答 2

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

有点长的例子,但我不想编辑掉东西,也许会破坏它。

于 2012-03-08T19:43:10.393 回答
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

快乐编码

于 2012-03-09T04:22:01.830 回答