Reputation: 138
I used this query:
Product::whereId($item->id)->sum(function ($row) {
return $row->quantity * ($row->variable ?? 1);
});
But I got this error:
production.ERROR: stripos() expects parameter 1 to be string, object given
I want to get the result of $row->quantity * $row->variable
as the sum, but some of $row->variable
are null so I used ($row->variable ?? 1)
.
Upvotes: 1
Views: 507
Reputation: 64476
I would suggest to perform such sum operation directly at database layer by doing some conditional aggregation
Product::whereId($item->id)
->sum(\DB::raw('quantity * (case when variable > 0 then variable else 1 end)'));
There are 2 main benefits of above approach
Upvotes: 1
Reputation: 446
Run sum function on a collection if your collection is small is fine
but if you have a huge collection, for example say you have 2000 items in it, then calculate the sum in mysql will be a good choice
in your code, you first get the result from DB and then run the sum operation of collection in php not in mysql
but the result is same
until you have to face the big collection do not worry about it
Upvotes: 0
Reputation: 138
I used get()
to get collection before sum and my problem solved.
so I changed my code to this:
Product::whereId($item->id)->get()->sum(function ($row) {
return $row->quantity * ($row->variable ?? 1);
});
Upvotes: 0
Reputation: 446
Yes, it throws exception because you must use string instead of function(closure)
use this for example
Product::selectRaw("sum(quantity * variable)")->whereId($item->id)->get();
Upvotes: 1