[英]How to filter a many to many relationship by a column in pivot table
My application has the following entities:我的应用程序具有以下实体:
Locations
Disciplines
Instructors
Disciplines
and Instructors
should be a many to many relationship, so in my Discipline
model I have the following: Disciplines
和Instructors
应该是多对多的关系,所以在我的Discipline
model 中,我有以下内容:
public function instructors() {
return $this->belongsToMany(
Instructor::class,
'location_discipline_instructors',
'discipline_id',
'instructor_id'
);
}
My pivot
table contains the following fields:我的
pivot
表包含以下字段:
location_id
discipline_id
instructor_id
I can use this relationship to fetch all disciplines
with the associated instructors
, but I need to filter these results by the location_id
in the pivot
table.我可以使用这种关系来获取相关
instructors
的所有disciplines
,但我需要通过pivot
表中的location_id
过滤这些结果。
How should I approach this?我应该如何处理这个?
I tried using wherePivot()
with location_id
, but with that approach, I ended up with a list of all system disciplines
with instructors
for any discipline
that had instructors
associated.我尝试将
wherePivot()
与location_id
一起使用,但通过这种方法,我最终得到了一个包含所有系统disciplines
的列表,其中包含与instructors
相关的任何discipline
的instructors
。 I continued to research and ended up with this solution:我继续研究并最终得到了这个解决方案:
Discipline::whereHas('instructors', function ($query) {
return $query->where('location_id', '=', $this->locationId);
})->with('instructors')->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.