php - Symfony2 Doctrine 查询生成器作为 FROM 子句中的子查询

标签 php symfony doctrine-orm

我使用查询构建器获得了一个查询,并将其分配给 $qb 变量。它在 PHP 和数据库中都运行良好。现在,我正尝试将该查询用作子查询,如下所示:

    $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?任何帮助都会非常有益。干杯!

最佳答案

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

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

这是为了在使用 DQL 时可以正确映射实体。

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

关于php - Symfony2 Doctrine 查询生成器作为 FROM 子句中的子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29243636/

相关文章:

php - 我应该升级到 PHP 5.3 吗?

php - Zend验证码html

symfony - Doctrine2 OneToMany - ManyToOne 返回空集合,数据库正常

mysql - 错字3流: "Result could not be converted to string" - get field content of query result

symfony - Doctrine内部查询设置参数

php - Magento - 将 SKU 数组添加到购物车

php - 包含来自 mysql 的数据的 Html 表

php - Symfony2.0.15 Doctrine-Fixtures Windows 命令行 fatal error

url - 获取网站的基本 url 并将其全局传递给 Symfony 2 中的 twig

php - DDD - 在面向文档的存储、PostgreSQL、MongoDB 中存储域对象