Symfony2 Doctrine查询构建器作为FROM子句中的子查询

时间:2015-03-24 21:55:22

标签: php symfony doctrine-orm

我使用查询构建器进行了查询,并将其分配给$qb变量。它从PHP和DB都可以正常工作。现在,我试图将该查询用作下面的子查询:

    $subQuery = $qb->getQuery()->getSql();
    $query = 'select res.some_name
              from ('.$subQuery.') as res';

但我得到以下例外:

Caused by Doctrine\DBAL\Driver\PDOException: SQLSTATE[HY000]: General error: 1 no such column: res.some_name

由于Doctrine已将$qb转换为类似于Doctrine转换原始SQL查询的内容。例如,有一个名为AS legalentity_name但它显示AS name1:

select res.some_name from (SELECT o0_.id AS id0, o0_.name AS name1, b1_.id AS id2, b1_.display AS display3, m2_.id AS id4, m2_.total AS total5 FROM Invoice i3_ INNER JOIN CodeableItem c4_ ON i3_.id = c4_.id INNER JOIN MonetaryItem m2_ ON i3_.id = m2_.id AND (1=1) INNER JOIN LineItem l5_ ON c4_.id = l5_.codeableItem_id LEFT JOIN MonetaryItem m6_ ON l5_.id = m6_.id AND (1=1) LEFT JOIN PresetLineItem p7_ ON c4_.id = p7_.codeableItem_id LEFT JOIN MonetaryItem m8_ ON p7_.id = m8_.id AND (1=1) INNER JOIN OrgUnit o0_ ON c4_.legalentity_id = o0_.id AND (1=1) INNER JOIN monetaryitem_listitem m9_ ON m2_.id = m9_.monetaryitem_id INNER JOIN BWListItem b1_ ON b1_.id = m9_.bwlistitem_id AND (1=1) INNER JOIN BWList b10_ ON b1_.bwlist_id = b10_.id AND (1=1) WHERE b10_.type = 'Vendor' GROUP BY c4_.legalentity_id, b1_.active, b1_.attributes, b1_.display, b1_.created, b1_.updated, b1_.lft, b1_.lvl, b1_.rgt, b1_.root, b1_.id, b1_.orgunit_id, b1_.bwlist_id, b1_.parent_id, b1_.rootou_id, m2_.created, m2_.updated, m2_.subtotal, m2_.total, m2_.description, m2_.id, c4_.number, c4_.externalId, c4_.status, c4_.overriddenDuringApproval, i3_.invoiceDate, i3_.dueDate, i3_.poNumber, m2_.rootou_id, c4_.image_id, c4_.legalentity_id, c4_.creator, c4_.owner_id ORDER BY o0_.name ASC, b1_.display ASC) as res

我的问题是:如何使用$subQuery中的原始SQL?任何帮助都会非常有益。干杯!

1 个答案:

答案 0 :(得分:3)

首先,DQL中的子查询是不可能的。见Selecting from subquery in DQL

其次,您将来自Doctrine查询语言(DQL)的计算SQL放入子查询中。这不起作用,因为数据库无法找到列,因为DQL为字符添加前缀字符/数值。

这样可以在使用DQL时正确映射实体。

您需要构建不使用DQL语言的子查询(停止使用该查询构建器,不确定是否有构建原始SQL的那个)。