![](/img/trans.png)
[英]Laravel - Saving to pivot table in many to many relationship with extra column
[英]How to filter a many to many relationship by a column in pivot table
我的應用程序具有以下實體:
Locations
Disciplines
Instructors
Disciplines
和Instructors
應該是多對多的關系,所以在我的Discipline
model 中,我有以下內容:
public function instructors() {
return $this->belongsToMany(
Instructor::class,
'location_discipline_instructors',
'discipline_id',
'instructor_id'
);
}
我的pivot
表包含以下字段:
location_id
discipline_id
instructor_id
我可以使用這種關系來獲取相關instructors
的所有disciplines
,但我需要通過pivot
表中的location_id
過濾這些結果。
我應該如何處理這個?
我嘗試將wherePivot()
與location_id
一起使用,但通過這種方法,我最終得到了一個包含所有系統disciplines
的列表,其中包含與instructors
相關的任何discipline
的instructors
。 我繼續研究並最終得到了這個解決方案:
Discipline::whereHas('instructors', function ($query) {
return $query->where('location_id', '=', $this->locationId);
})->with('instructors')->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.