繁体   English   中英

Doctrine2:左连接中的 SUM

[英]Doctrine2: SUM in left join

我需要使用 Doctrine 进行查询,但我不知道该怎么做。

我需要的是要支付的金额

我有两个表:

订购订单商品

我想对订单商品的所有价格求和,然后从订单中减去已付款、优惠券和 user_credit。

Order
| ID |      Paid |     Coupon | UserCredit |
|----|-----------|------------|------------|
|  1 |     25.00 |      50.00 |      15.00 |
|  2 |     50.00 |       0.00 |      10.00 |

OrderItems
| ID | OrderID | Qty | SinglePrice |   Price |
|----|---------|-----|-------------|---------|
|  1 |       1 |   2 |       50.00 |  100.00 |
|  2 |       1 |   1 |      100.00 |  100.00 |
|  3 |       2 |   1 |      150.00 |  150.00 |

我需要总和:200.00

1: 200 - 25 - 50 - 15 = 110

2:150 - 50 - 0 - 10 = 90

$query = $this->entityQueryBuilder()
    ->select('(SUM(oi.price) - o.paid - o.coupon - o.user_credit) AS total')
    ->from(Order::class, 'o')
    ->leftJoin('o.items', 'oi')
    ->where('o.config = :config')
    ->andWhere('o.status < :status')
    ->setParameter('config', $this->getConfig())
    ->setParameter('status', 2)
    ->groupBy('o.id')
    ->getQuery();

return $query->getResult();

如果有人能帮我解决这个问题,我将不胜感激。

谢谢。

更新:通过上面的查询,我得到了很多行,但我只需要一个具有整体结果的行。

更新2:我现在已经解决了如下。 但我想知道它是否有效:

$query = $this->entityQueryBuilder()
    ->select('(SUM(oi.price) - o.paid - o.coupon - o.user_credit) AS total')
    ->from(Order::class, 'o')
    ->leftJoin('o.items', 'oi')
    ->where('o.config = :config')
    ->andWhere('o.status < :status')
    ->setParameter('config', $this->getConfig())
    ->setParameter('status', 2)
    ->groupBy('o.id')
    ->getQuery();

$result = $query->getResult();

$sum = array_sum(array_column($result, 'total'));

return $sum;

你需要:

  • 对订单使用子查询
  • 仅汇总订单商品的价格

尝试:

$query = $this->entityQueryBuilder()
    ->select('(SELECT SUM(o.paid - o.coupon - o.user_credit) FROM' . Order::class . ' o) AS paidTotal')
    ->addSelect('SUM(oi.price) AS amount_to_pay')
    ->from(Order::class, 'o')
    ->leftJoin('o.items', 'oi')
    ->where('o.config = :config')
    ->andWhere('o.status < :status')
    ->setParameter('config', $this->getConfig())
    ->setParameter('status', 2)
    ->getQuery();

$totals = $query->getSingleResult();
$total = $totals['amount_to_pay'] - $totals['paidTotal'];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM