我需要用Doctrine编写这个查询。如何使用 QueryBuilder 写下来?
SELECT charges.id, charges.currency, charges.total_transactions,
charges.total_volume, charges.commission, refunds.total_payouts
FROM
(SELECT ...very long query...) charges
LEFT JOIN
(SELECT ...very long query...) refunds
ON charges.id = refunds.id AND charges.currency = refunds.currency
您可以使用本机 SQL 并将结果映射到实体:
use DoctrineORMQueryResultSetMapping;
$rsm = new ResultSetMapping;
$rsm->addEntityResult('AppBundle:Charges', 'charges')
->addEntityResult('AppBundle:Refunds', 'refunds')
->addFieldResult('charges', 'id', 'id')
->addFieldResult('charges', 'currency', 'currency')
->addFieldResult('charges', 'total_transactions', 'total_transactions')
->addFieldResult('charges', 'total_volume', 'total_volume')
->addFieldResult('charges', 'commission', 'commission')
->addFieldResult('refunds', 'total_payouts', 'total_payouts')
;
$sql = "
SELECT
charges.id,
charges.currency,
charges.total_transactions,
charges.total_volume,
charges.commission,
refunds.total_payouts
FROM
(SELECT ...very long query...) charges
LEFT JOIN
(SELECT ...very long query...) refunds ON charges.id = refunds.id AND charges.currency = refunds.currency
WHERE some_field = ?
";
$query = $this->getEntityManager()->createNativeQuery($sql, $rsm);
$query->setParameter(1, $name);
$entities = $query->getResult();
你可以像这样使用DQL
:
$dql = "SELECT ...";
$q = $entityManager->createQuery($dql)->setParameters($arrayParameters);
$result = $q->execute();
或每个子查询的QueryBuilder
,例如:
// subquery 1
$subQuery1 = $entityManager->createQueryBuilder()
->select('...')
->from('...')
->getDQL()
;
// subquery 2
$subQuery2 = ...
// etc
// ...
// main query
$query = $entityManager->createQueryBuilder()
->select('...')
->from('...', $subQuery1)
->leftJoin('...', $subQuery1->getDQL()),
->where()
;
PS:我只是尝试为您提供要点...希望现在你有线索...
现在我发现这是不可能的。
斯托夫创建的评论:
DQL 是关于查询对象的。在 FROM 子句中支持子选择意味着 DQL 分析器无法再生成结果集映射(因为子查询返回的字段可能不再与对象匹配(。
这就是为什么它不能被支持的原因(仅在没有水化的情况下运行查询的情况下支持它是不可行的 IMO,因为这意味着查询解析需要依赖于执行模式(。
在您的情况下,最好的解决方案可能是运行SQL查询(因为您正在获得标量,因此无论如何都不需要ORM水合(
来源: https://github.com/doctrine/doctrine2/issues/3542