【问题标题】:How to get sum of related column values in Laravel?如何在 Laravel 中获取相关列值的总和?
【发布时间】:2021-01-11 10:55:28
【问题描述】:

我有 4 张桌子。 (我的每张表都有更多的列,但这里只列出所需的一次)

order_header:

id
ship_method
order_status

ship_method:

id

状态:

code

order_items:

header_id

这是我的 order_header 模型与 order_items 的关系:

public function order_items()
    {
        return $this->hasMany('\App\Models\OrderProduct', 'header_id', 'id');
    }

这是我获取 order_header 数据的最终查询:

$orders = OrderHeader::select('order_header.*', 'shipping_method.name as shipping_method_name', 'status.description as status_name')
                            ->join('shipping_method', 'shipping_method.id', '=', 'order_header.ship_method')
                            ->join('status', 'status.code', '=', 'order_header.order_status')
                            ->with(['order_items', 'creator:id,username', 'updater:id,username']);

这将返回 $orders 及其 order_items:

例如:id 17

    "data": {
        "id": 17,
        "shipping_method_name": "shipping method 1 update",
        "status_name": "pending",
        "order_items": [
          {
            "id": 35,
            "header_id": 17,
            "order_quantity": 5,
            "total_line_value": "20.00",
          },
          {
            "id": 36,
            "header_id": 17,
            "order_quantity": 5,
            "total_line_value": "20.00",
          },
          {
            "id": 37,
            "header_id": 17,
            "order_quantity": 5,
            "total_line_value": "20.00",
          }
}

现在如何将 order_items 的 order_quantity 和 total_line_value 的值相加并显示? 例如:在 id 17 以上,我需要再显示两行 order_quantity_sum: 15total_line_value_sum: 60。 如何实现这一点,请有人帮助我。提前致谢。

【问题讨论】:

  • 这能回答你的问题吗? Laravel Eloquent Sum of relation's column
  • 感谢您的快速回复,但这个答案对我没有帮助。如果您能在这里帮助我,将不胜感激。
  • 我尝试添加这一行 $orders->order_items->sum('order_quantity');我收到一条错误消息:Eloquent 构建器实例上不存在属性 [order_items]。
  • 检查this
  • 谢谢@iamab.in。通过使用接受的答案,我可以实现我想要的,但它也会返回带有已删除记录的总和。现在正在寻找解决方案。

标签: laravel eloquent


【解决方案1】:

您可以在选择中使用DB::raw('sum('order_items.order_quantity') as total_order_items')。同样的方法也适用于总行值

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 2018-12-04
    • 2021-08-09
    • 2020-08-30
    • 1970-01-01
    相关资源
    最近更新 更多