简体   繁体   English

如何通过 pivot 表中的列过滤多对多关系

[英]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: DisciplinesInstructors应该是多对多的关系,所以在我的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相关的任何disciplineinstructors 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.

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