Rediska's avatar

How to use wherehas condition multiple times?

I'll try to explain in more detail. With this request I get all categories that have products and product color, for example black. I want to add one more condition to this request - the discount field for each of these products must not be equal to null.

$categories = Category::whereHas('products.colors', function ($query) use ($color) {
                $query->where('title', $color);
            })->get();

This works fine.

I'm trying to add one more condition:

$categories = Category::whereHas('products.colors', function ($query) use ($color) {
                $query->where('title', $color);
            })
                ->whereHas('products', function ($query) {
                    $query->where('sale', '!=', null);
                })
                ->get();

But this doesn't work as it should. How can I correct my request?

0 likes
2 replies
MohamedTammam's avatar
Level 51
$categories = Category::whereHas('products', function ($productQuery) use ($color) {
  $productQuery->whereNotNull('dicount')->whereHas('colors', function($colorQuery) use ($color) {
	  $colorQuery->where('title', $color);
  });
})->get();

1 like

Please or to participate in this conversation.