使用Doctrine加入两个SELECT

时间:2017-08-09 15:10:25

标签: mysql symfony doctrine-orm

我需要用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

3 个答案:

答案 0 :(得分:1)

您可以像这样使用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:我只是试着为你提供要点......希望你现在有线索......

答案 1 :(得分:1)

您可以使用DevicePolicyManager.setPackagesSuspended()并将结果映射到实体:

use Doctrine\ORM\Query\ResultSetMapping;

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

答案 2 :(得分:0)

现在我发现它是不可能的。

  

由stof创建的评论:

     

DQL是关于查询对象的。支持FROM子句中的子选择意味着DQL解析器不再能够构建结果集映射(因为子查询返回的字段可能不再与该对象匹配)。

     

这就是为什么它不能被支持(仅支持它运行查询而没有水合作用的情况是一个禁止的IMO,因为它意味着查询解析需要依赖于执行模式)。

     

在您的情况下,最好的解决方案可能是运行SQL查询(因为您正在获得标量,无论如何您都不需要ORM水合作用)

来源:https://github.com/doctrine/doctrine2/issues/3542