首页 > 解决方案 > 如何通过数据透视表中的列过滤多对多关系

问题描述

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

Disciplines并且Instructors应该是多对多的关系,所以在我的Discipline模型中,我有以下内容:

public function instructors() {
    return $this->belongsToMany(
        Instructor::class,
        'location_discipline_instructors',
        'discipline_id',
        'instructor_id'
    );
}

我的pivot表包含以下字段:

我可以使用这种关系来获取所有disciplines关联的instructors,但我需要通过表location_id中的过滤这些结果pivot

我应该如何处理这个?

标签: phplaraveleloquent

解决方案


我尝试使用wherePivot()with location_id,但通过这种方法,我最终得到了所有系统的列表,disciplines其中instructors包含任何discipline关联的系统instructors。我继续研究并最终得到了这个解决方案:

Discipline::whereHas('instructors', function ($query) {
    return $query->where('location_id', '=', $this->locationId);
})->with('instructors')->get();

推荐阅读