Symfony2 Query Builder“SELECT where sum children> 0”

时间:2016-01-22 05:10:13

标签: php mysql symfony query-builder

我正在尝试收集包含子项OrderPayments的订单结果集。我想只有订单,其中orderpayments.amount的总和> 0

到目前为止,我有这个,但无法让它工作,我得到了

未找到列:'where子句'

中的未知列'sclr_0'
    // Create the Query Builder
    $qb = $this->createQueryBuilder('o')->select('o');

    // Joins
    $qb->leftJoin('o.orderPayments', 'op')->addSelect('op')->addSelect('SUM(op.amount) AS total_sum');

    // Criteria
    $qb->where('total_sum > 0');
    $qb->andWhere('o.dateDeleted IS NULL');

    // Return the result
    return $qb->getQuery()->getResult();

1 个答案:

答案 0 :(得分:1)

您是否在数据库中尝试过SQL查询?

您的查询类似于:

SELECT o.*, SUM(op.amount) AS total 
FROM order o 
LEFT JOIN order_payement op on o.id = op.order_id
WHERE total > 0;

此查询不适用于mysql,不能在WHERE子句中对SELECT子句使用操作结果。

您的查询必须如下:

SELECT o.*, SUM(op.amount) AS total 
FROM order o 
LEFT JOIN order_payement op on o.id = op.order_id
HAVING SUM(op.amount) > 0
GROUP BY o.id;

您的查询构建器将是:

$qb = $this->createQueryBuilder('o')
   ->select('o');
   ->leftJoin('o.orderPayments', 'op')
   ->addSelect('op')
   ->addSelect('SUM(op.amount) AS total_sum')
   ->Where('o.dateDeleted IS NULL')
   ->having('SUM(op.amount) > 0')
   ->grouBy('o.id');