Laravel Conditional query on relationships sum
Im trying to build a query to fetch all Orders
that has relational products
, where the products
amount is greater or equal to a value.
An order
can have many products
, and products have a property named amount
.
Now what I need to do is fetch Orders
, where the total amount of products
(sum of property amount, on all related products
) meets the criteria.
$orders = Order::
when( $request->amount, function($query) use ($request){
$query->whereHas('products', function($q) use ($request){
$q->where('amount', '>=', $request->amount);
});
})
->get();
This code works as far as to check the that the amount for every connected product is greater or equal to the input, but I can’t wrap my head around getting it to check the sum
of amount
on all connected products
. Any tips?
from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-conditional-query-on-relationships-sum/
via Lzo Media
No comments:
Post a Comment