Reputation: 961
I have a table with:
Events
Cities
Clubs
The relations are as following:
Event
'hasOne' Club
, and a Club
'hasMany' Event
s.Club
'hasOne' City
and a City
'hasMany' Club
s.I want to add a filter to my query to get all events where the club.city == 'Oklahoma'
. This is what I tried:
$events = Event::where( 'accepted', 1 )
->with( [ 'club.city', 'organisation' ] )
->where( 'club.city.name', 'Rotterdam' )
->orderBy( 'created_at', 'asc' )
->paginate( 6 );
Upvotes: 0
Views: 488
Reputation: 50491
You can use whereHas to filter based on existance of a condition on a relationship.
$events = Event::where( 'accepted', 1 )
->with( [ 'club.city', 'organisation' ] )
->whereHas('club.city', function ($q) use ($cityname) {
$query->where('name', $cityname);
})->orderBy( 'created_at', 'asc' )
->paginate( 6 );
Upvotes: 1