Reputation: 1046
I'm a bit confused regarding the AND WHERE clause whith collections.
The following query gets all the users owning a car licence OR a motorbike licence:
User::whereHas('licences', function($query) {
$query->whereIn('type', ['car', 'motorbike']);
})->get();
Now how to get all the users owning a car licence AND a motorbike licence ?
Upvotes: 0
Views: 124
Reputation: 12188
try duplication your whereHas:
$wantedLicences= ['car', 'motorbike'];
$query=User::query();
foreach($wantedLicences as $wantedLicence)
{
$query=$query->whereHas('licences', function($query)use($wantedLicence) {
$query->where('type', $wantedLicence);
})
}
Upvotes: 1
Reputation: 50481
Assuming a User can't have more than one type of a license then you would adjust the whereHas
to check that the count of related records equals 2:
User::whereHas('licenses', function ($query) {
$query->whereIn('type', ['car', 'motorbike']);
}, '=', 2)->get();
Laravel 8.x Docs - Eloquent - Relationships - Querying Relationship Existence
Upvotes: 2
Reputation: 723
The query should be like this for getting users owning a car and a motorcycle
User::whereHas('licences', function($query) {
$query->where('type','car')->where('type','motorbike');
})->get();
Upvotes: -1