php - 如何通过数据透视表中的列过滤多对多关系
问题描述
我的应用程序具有以下实体:
Locations
Disciplines
Instructors
Disciplines
并且Instructors
应该是多对多的关系,所以在我的Discipline
模型中,我有以下内容:
public function instructors() {
return $this->belongsToMany(
Instructor::class,
'location_discipline_instructors',
'discipline_id',
'instructor_id'
);
}
我的pivot
表包含以下字段:
location_id
discipline_id
instructor_id
我可以使用这种关系来获取所有disciplines
关联的instructors
,但我需要通过表location_id
中的过滤这些结果pivot
。
我应该如何处理这个?
解决方案
我尝试使用wherePivot()
with location_id
,但通过这种方法,我最终得到了所有系统的列表,disciplines
其中instructors
包含任何discipline
关联的系统instructors
。我继续研究并最终得到了这个解决方案:
Discipline::whereHas('instructors', function ($query) {
return $query->where('location_id', '=', $this->locationId);
})->with('instructors')->get();
推荐阅读
- windows - 如何在 Powershell 中指定文件夹位置和文件类型
- java - 使用 Spring Data 将两个对象合并到 Map
- workflow - 在 ServiceNow 中,如何在工作流中回滚到“等待条件”之前的状态?
- python - 通过 csv 缩短控制台输出
- android - 如何阻止 Android Studio 打开多个窗口?
- sql - 对包含整数、小数和字符串的字符串字段进行排序 SQL
- azure - 如何删除具有 RecoveryServicesVaults 和备份项目的 Azure 资源组
- arrays - 使用 Spark Dataframe (Scala) 中的另一列数组创建一列数组
- python - 为什么 scipy.optimize.curve_fit 反复评估初始猜测(并且可能代价高昂)?
- javascript - 为锚链接 URL 查询添加动态文本