Search code examples
phpmysqllaraveleloquentlaravel-query-builder

Laravel Query Builder get only item with specific progress


Good day, I'm trying to get orders with products that have a specific products progress.

enter image description here

My Laravel query looks like this:

return Order::whereHas('products.progress', function (Builder $query) {
    $query->where('progress_id', 100)
        ->orWhereBetween('progress_id', [160, 240]);
      })
    ->with('products.progress')
    ->select('orders.id', 'orders.customer_id', 'orders.created_at')
    ->get();

In the query I set a where and whereBetween, the last Product has the progress_id 50 that one should not be loaded into the order.

How to do it? Thank you for reading.


Solution

  • i think you want to Constraining Eager Loads

    so your (wheres) should be on the loading ...

    return Order::with(['products'=>function($query){
            $query->whereHas('progress',function ($query){
                $query->where('progress_id', 100)
                    ->orWhereBetween('progress_id', [160, 240]);
            })->with('progress');
        }])
            ->select('orders.id', 'orders.customer_id', 'orders.created_at')
            ->get();