繁体   English   中英

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

[英]How to filter a many to many relationship by a column in pivot table

我的应用程序具有以下实体:

  • Locations
  • Disciplines
  • Instructors

DisciplinesInstructors应该是多对多的关系,所以在我的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相关的任何disciplineinstructors 我继续研究并最终得到了这个解决方案:

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