简体   繁体   中英

Use Eloquent to filter by pivot table in Laravel 5.3

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 .

You can use whereHas as:

$events = $events->whereHas('supervisors', function($q) use($supervisors) {
   $q->whereIn('supervisor_id', $supervisors);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM