I need to make an advanced query in Laravel hopefully using Eloquent to make that a collection but a query builder or raw normal SQL query is acceptable.
I have users table with User model having relation:
public function roles()
{
return $this->belongsToMany(Role::class,'users_roles');
}
I have roles table, with Role model having relation:
public function users()
{
return $this->belongsToMany(User::class,'users_roles');
}
So, I have users_roles table with columns [user_id, role_id]
, so I can have users with multiple roles
I want to get all users with roles different from a certain role, for example get all users that are all kind of roles except role of id 1
how to do that?
2
Answers
You can pass a where clause to
withWhereHas
to defined rules on which models to return depending on relations, like so:You can use the whereDoesntHave method provided by Eloquent to achieve this.