我想用Symfony 2.x在Doctrine中表示以下SQL查询:
SELECT (SELECT sum(J.amount) FROM journals as J WHERE debit_id = ?) - (SELECT sum(J.amount) FROM gold.journals as J WHERE credit_id = ?)
我花了一些时间在querybuilder上,然后转到DQL Query:
$q = $this->getEntityManager()->createQuery('SELECT (SELECT sum(J.amount) FROM xxx\Entity\Journal as J WHERE debit = ?) - (SELECT sum(J.amount) FROM xxx\Entity\Journal as J WHERE credit = ?))');
这两者都导致了一些语法异常:
Syntax Error] line 0, col 97: Error: Expected Doctrine\ORM\Query\Lexer::T_FROM, got '-'
什么是运行此查询的最佳doctrine / symfony方式?
答案 0 :(得分:1)
尝试this method在Doctrine中执行嵌套查询。
答案 1 :(得分:1)
Oukay,现在发现了一个解决方案:
$qb = $this->getEntityManager()->createQueryBuilder();
$x = $qb->select()
->addSelect('(SELECT sum(J1.amount) FROM xxx\Entity\Journal as J1 WHERE J1.debit = :id)')
->addSelect('(SELECT sum(J2.amount) FROM xxx\Entity\Journal as J2 WHERE J2.credit = :id)')
->from("xxx\Entity\Journal", "tmp")
->setMaxResults(1)
->setParameter('id', 1);
return print_r($x->getQuery()->getArrayResult()[0],true);
它有点难看,因为它看起来像Query Builder NEEDS - > from()被设置为某种东西......这就是为什么我使用setMaxResults来限制输出。它仍然不是完美的解决方案,但是......我很高兴开始。
答案 2 :(得分:0)
尝试使用以下内容:
$q = $this->getEntityManager()->createQuery('SELECT
(
(SELECT sum(J.amount) FROM xxx\Entity\Journal as J WHERE debit = ?)
-
(SELECT sum(J.amount) FROM xxx\Entity\Journal as J WHERE credit = ?)
) as total
');
然后获取查询结果的标量值。
$q->getQuery->getSingleScalarResult();