Ole Haugset
Ole Haugset

Reputation: 3797

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?

Upvotes: 1

Views: 1457

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

Use this:

$orders = Order::
when( $request->amount, function($query) use ($request){
    $query->whereHas('products', function($q) use ($request){
        $q->select(DB::raw('sum(amount) amount'))
            ->having('amount', '>=', $request->amount);
    });
})
->get();

Upvotes: 4

Related Questions