【问题标题】:Doctrine2: SUM in left joinDoctrine2:左连接中的 SUM
【发布时间】:2019-12-12 19:32:41
【问题描述】:

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

【问题讨论】:

    标签: php mysql doctrine-orm dql


    【解决方案1】:

    你需要:

    • 对订单使用子查询
    • 仅对订单商品的价格求和

    试试:

    $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'];
    

    【讨论】:

    • 非常感谢您的回答。我想我错误地描述了我的要求。我又更新了帖子。
    猜你喜欢
    • 2017-01-15
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 2015-12-11
    相关资源
    最近更新 更多