Reputation: 3971
Is there a 'whereDoesNotHave' kind of method in Laravel to get records that have no relations?
I have a query that checks if Users has a Team, or their name is David, but just don't know how to write this query:
User::where(function($query){
$query->where('name', 'David')->orWhere($this->teams->count() , '<' , 1);
})
->get();
I need something like this.
UPDATE
Forgot to mention - the relation is many-to-many, users can have multiple teams
Upvotes: 5
Views: 3055
Reputation: 3190
In your User Model, you probably have a relation to Team Model
// in User Model
public function team()
{
return $this->belongsTo('App\Team', 'team_id');
}
This would be the default way to relate a User to a Team, logically.
If this is the case, that means you have a team_id field in your users table. So only thing you have to do, is to look for Users with null team_id field.
And that would be;
$q = User::where('team_id',null)->orWhere('name','David')->get();
Edit: If your relation is many to many however (Each user may belong to multiple teams), you should use Eloquent's has() method;
$users = User::has('teams', '0')->orWhere('name', 'David')->get();
NOTE: as patricus pointed in his answer;
Using Eloquent method doesntHave()
also works, and seems more proper in this case.
Upvotes: 2
Reputation: 62238
You can use the doesntHave()
method:
$users = User::doesntHave('teams')->orWhere('name', 'David')->get();
If you need to "OR" it, the second parameter lets you change that:
$users = User::where('name', 'David')->doesntHave('teams', 'or')->get();
Upvotes: 4