mkl_capitao2
mkl_capitao2

Reputation: 95

Laravel - How can i filter a many to many model, where the relationship is absent by further columns?

So i have this situation, where a User can be assigned many Products, and a product can have many Users. So M-M relationship.

I can use the below, to get all products the user does not have (think of it as all products not assigned to this user):

$products = Product::whereDoesntHave('users', function($query) use ($user) {
                $query->where('uid', $user->id);
            });

However, now i added a new column to the products table called status. I want to adapt the above query so it gets me all products user does not have (same as above), but in addition only if this products status value is not equal to 1. So it can be 0 or Null. I tried the below, but it doesnt work (still shows products with status of 1).

$products = Product::where('status', 0)->orWhereNull('status')->
            whereDoesntHave('users', function($query) use ($user) {
                $query->where('uid', $user->id);
            });

What am I getting wrong?

Upvotes: 1

Views: 324

Answers (1)

Brian Lee
Brian Lee

Reputation: 18187

Pass a closure to the where clause to group the status conditions together.

$products = Product::where(function ($query) {
  $query->where('status', 0)->orWhereNull('status');
})->whereDoesntHave('users', function($query) use ($user) {
  $query->where('uid', $user->id);
})->get();

Upvotes: 1

Related Questions