[英]Use Eloquent to filter by pivot table in Laravel 5.3
我正在使用Laravel(5.3)雄辯的ORM,並嘗試使用數據透視表進行過濾。 我有三個表: events
, supervisors
和event_has_supervisors
。 現在,我只想將所有事件分配給某個主管。
在我的事件模型中,我得到了:
public function supervisors() {
return $this->belongsToMany(Supervisor::class, 'event_has_supervisors')->withPivot('hours');
}
現在,在我的控制器中,我需要查詢所有事件,並提供一些條件:
$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);
顯然,最后一個子句不起作用,因為事件表中沒有此類屬性。 但是在這種情況下,如何查詢我的數據透視表? 我希望分配給該事件的任何主管都是$supervisors
任何$supervisors
。
您可以將whereHas
用作:
$events = $events->whereHas('supervisors', function($q) use($supervisors) {
$q->whereIn('supervisor_id', $supervisors);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.