jeudi 25 octobre 2018

Laravel Collection Sum Multiple Columns in Collection

I have been reading about collections in Laravel. Currently I am aware of how to use it however I have a question about the sum() function.

According to the docs it can be used like this:

collect([1, 2, 3, 4, 5])->sum();

And also like this:

$collection = collect([
    ['name' => 'JavaScript: The Good Parts', 'pages' => 176],
    ['name' => 'JavaScript: The Definitive Guide', 'pages' => 1096],
]);

$collection->sum('pages');

Which is fine and I understand, however now I have an array with nested objects and I would like to know how I can achieve something like this in laravel:

$collection = collect([
    ['name' => 'JavaScript: The Good Parts', 'pages' => 176, 'price' => 100.00],
    ['name' => 'JavaScript: The Definitive Guide', 'pages' => price, 'pages' => 150.00],
]);

$collection->sum(['pages', 'prices']);

Which would obviously return either an array like this:

[1272, 250]

or on collection / object like this:

{"total_pages": 1272, "total_price": 250}

in short I would like to know how I can sum and return the results of multiple columns in a laravel collection instead of doing this twice:

$collection->sum('pages');
$collection->sum('price');

Since i assume that would cause multiple loops over the collection or am I wrong?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire