为了账号安全,请及时绑定邮箱和手机立即绑定

在 Laravel 中使用了 groupby 的总和

在 Laravel 中使用了 groupby 的总和

PHP
呼唤远方 2022-01-02 16:22:08
我已经通过inventory_id 对列价格组求和。此外,我需要计算总价。$record = ProductDetails::with('inventoryName')->whereDate('created_at', '=', date($date))      ->select('inventory_id',DB::raw('sum(price) as item_price'),DB::raw('sum(quantity) as quantity'))->groupBy('inventory_id')->get();我的输出是:[  {    inventory_id: 9,    item_price: 30,    quantity: 30,    inventory_name: [      {        id: 9,        name: "sugar"      }    ]  },  {    inventory_id: 10,    item_price: 70,    quantity: 70,    inventory_name: [      {        id: 10,        name: "oil"      }    ]  }]现在我需要计算总价。如何做到这一点。
查看完整描述

1 回答

?
暮色呼如

TA贡献1853条经验 获得超9个赞

您可以使用Laravel Collection: SUM 方法。


1. If $record is already a collection:

echo $record->sum('item_price');


2. If $record is an array.

$collection = collect($record);

$collection->sum('item_price');


查看完整回答
反对 回复 2022-01-02
  • 1 回答
  • 0 关注
  • 335 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号