![](/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.