0

Is it possible to groupBy a laravel collection with sum() on a column? The collection looks something like this:

    [
    {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:[]}
    ]

Row 2 and 3 are the same and I need to sum() the quantity.

Row 4 and 5 are the same and I need to sum() the quantity.

The result should be something like this:

  [
    {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:[]},
    ]
Victordb
  • 519
  • 1
  • 11
  • 25
  • are these Eloquent models? If so, It might be better to do it from the database query level – Chinonso Chukwuogor Aug 23 '18 at 17:51
  • Yes is a eloquent collection. The option is a relation and I can't figure out how to query group by relation content. – Victordb Aug 23 '18 at 18:14
  • Can you get the ID (or any other field) to be unique for "same" lines? that way you could groupBy ID the collection. You could archive this with some collection processing, but I don't know if a one-method way exists for this. – Mtxz Aug 23 '18 at 21:42
  • I could edit the database but what could I make unique besides making a string of options? And if I do that wouldn't that defeat the purpose of having the junction table transacation_options? – Victordb Aug 24 '18 at 07:06
  • Does this answer your question? [Laravel Eloquent: sum with groupBy](https://stackoverflow.com/questions/24887708/laravel-eloquent-sum-with-groupby) – mickmackusa Feb 25 '20 at 20:19

1 Answers1

0

You can show this package

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