Paul
Paul

Reputation: 858

Laravel whereHas relationship conditionals not working as expected

I have a Product model which is connected to a Variant model. This variant is then connected to an Option.

My query:

$query = Product::orderBy($params['orderBy'], $params['sort']);

$query->whereHas('variants.options', function($query) use ($params) {
  $query->where('options.name', '10');
  $query->where('options.name', 'rose');
  $query->where('inventory_quantity', '>', 0);
});

For some reason this is not returning the Products which have a Variant that has two seperate Options connected (10 and Rose) and where the variant's inventory_quantity is bigger than 0.

It works properly when I remove the $query->where('options.name', 'rose'); line.

The variants are connected to options via the variant_option pivot table. The values are properly stored in that table.

Upvotes: 0

Views: 154

Answers (2)

Namoshek
Namoshek

Reputation: 6544

You are querying products which have an option (through variants) which has a name that is 10 and rose at the same time. Of course that can never be true.

Instead, you need to add two whereHas() blocks inside a whereHas('variants') block to assert both options:

$products = Product::query()
    ->whereHas('variants', function ($query) {
        $query->whereHas('options', function ($query) {
            $query->where('options.name', '10');
        })
        ->whereHas('options', function ($query) {
            $query->where('options.name', 'rose');
        })
        ->where('inventory_quantity', '>', 0);
    })
    ->orderBy($params['orderBy'], $params['sort'])
    ->get();

This literally reads as:
Give me all products which have at least one variant that is in stock and has at least two options of which one is named 10 and one is named rose.

Upvotes: 1

Yasin Patel
Yasin Patel

Reputation: 5731

Try this query :

$query->whereHas('variants.options', function($query) use ($params) {
  $query->where(function($q){
    $q->where('options.name', '10');
    $q->orwhere('options.name', 'rose');
  })
  $query->where('inventory_quantity', '>', 0);
});

Upvotes: 0

Related Questions