Laravel eloquent many to many relation deep conditions

139 Views Asked by At

I have two Model named Product and Category. Admin can change the status of Product and Category. Here Product and Category has many to many relations. So that, all Product can belongs to multiple Category

Now at my user panel, I want to show that all Product whose all Category's status is active.

3

There are 3 best solutions below

0
Murtaja Ahmed Noyeem On BEST ANSWER

It works for me, got all the products that have all the categories active. First time I thought complicated so I didn't solve.

$products = Product::whereDoesntHave('catagories',function($category){
    $category->where('status','!=',1);
});
2
Md. Sakir Ahmed On

The solution is:

$products = Product::with('category')
    ->whereHas('category', function ($query) {
        $query->where('status', 'active'); // use your column & condition
    })
  ->get();
1
Ahmed Hani On

you can do this in your product model

public function categories(){
    return $this->belongsToMany(Category::class, CategoryProduct::class, 'product_id', 'category_id');
//->withPivot([]); if you need anything from the pivot table for any reason you can add the column names in the array
}

this is assuming that the pivot table have the columns product_id and category_id

$products = Product::with('categories')
    ->whereHas('categories', function ($query) {
        $query->where('categories.status', 'active');
    })
  ->get();

inside the where the word categories is the table name