Reputation: 325
I am using Laravel's (5.3) Eloquent ORM and try to filter using a pivot table. I have three tables: events
, supervisors
and event_has_supervisors
. Now I just want all events assigned to a certain supervisor.
In my Event Model I got this:
public function supervisors() {
return $this->belongsToMany(Supervisor::class, 'event_has_supervisors')->withPivot('hours');
}
In my Controller I now need to query all events, given a few criteria:
$events = Event::with($relations);
// This works well: get all Events in one or more given cities
$events = $events->whereIn('events.place_id', $cities);
// This does not work
$events = $events->whereIn('events.supervisor_id', $supervisors);
Obviously, the last where-clause doesn't work, because there is no such attribute on my events table. But how can I query my pivot table in this case? I want any of the supervisors assigned to the event to be any of the supervisors in $supervisors
.
Upvotes: 1
Views: 2039
Reputation: 17658
You can use whereHas
as:
$events = $events->whereHas('supervisors', function($q) use($supervisors) {
$q->whereIn('supervisor_id', $supervisors);
});
Upvotes: 2