Laravel集合groupBy()与sum()

时间:2018-08-23 17:29:24

标签: laravel collections laravel-5.6 laravel-collection

是否可以在列上使用sum()将laravel集合分组? 该集合看起来像这样:

    [
    {id: 1, name: A, quantity: 1, price: 20, options:[{id:10,name:AC}{id:13,name:AB}]},
    {id: 1, name: A, quantity: 5, price: 15, options:[{id:20,name:AV},{id:30,name:AZ}]},
    {id: 1, name: A, quantity: 10, price: 15, options:[{id:20,name:AV},{id:30,name:AZ}]},
    {id: 1, name: A, quantity: 2, price: 10, options:[]},
    {id: 1, name: A, quantity: 4, price: 10, options:[]}
    ]

第2行和第3行相同,我需要对数量进行求和。

第4行和第5行相同,我需要求和()数量。

结果应该是这样的:

  [
    {id: 1, name: A, quantity: 1, price: 20, options:[{id:10,name:AC}{id:13,name:AB}]},
    {id: 1, name: A, quantity: 15, price: 15, options:[{id:20,name:AV},{id:30,name:AZ}]},
    {id: 1, name: A, quantity: 6, price: 10, options:[]},
    ]

1 个答案:

答案 0 :(得分:0)

您可以显示此package

$invoices = Invoice::withSum('items:price')->get();