Php 如何恰当地界定属于多个关系的范围

Php 如何恰当地界定属于多个关系的范围,php,laravel,eloquent,Php,Laravel,Eloquent,我的应用程序具有以下实体: 位置 学科 讲师 学科和讲师应该是多对多的关系,因此在我的学科模型中,我有以下几点: 公共职能讲师(){ 返回$this->belongtomany( 讲师:班级, “地点、纪律、教员”, “纪律id”, “身份证” )->withPivot(['location_id']); } Mypivot表包含以下字段: location\u id 专业id 讲师id 为了获得相关讲师的学科列表,我做了如下操作: return Discipline::with(['

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

  • 位置
  • 学科
  • 讲师
学科
讲师
应该是多对多的关系,因此在我的
学科
模型中,我有以下几点:

公共职能讲师(){
返回$this->belongtomany(
讲师:班级,
“地点、纪律、教员”,
“纪律id”,
“身份证”
)->withPivot(['location_id']);
}
My
pivot
表包含以下字段:

  • location\u id
  • 专业id
  • 讲师id
为了获得相关讲师的学科列表,我做了如下操作:

return Discipline::with(['instructors' => function ($query) {
    $query->where('location_id', '=', $this->locationId);
}])
    ->whereHas('instructors', function ($query) {
        return $query->where('location_id', '=', $this->locationId);
    })
    ->get();
返回规程::whereHas('instructors',function($query){
返回$query->where('location_id','=',$this->locationId);
})->with('instructors')->get();
起初,我认为这正是我所需要的——这很接近,但不是我想要的。以下是我得到的回复示例:

{
"纪律":四,,
“纪律”:“旧轮胎销售”,
“updatedBy”:空,
“讲师”:[
{
“id”:5,
“名字”:“雅克”,
“姓氏”:“莫顿”,
“支点”:{
"纪律":四,,
“id”:5,
“位置ID”:27
}
},
{
“id”:1,
“名字”:“系统”,
“lastname”:“管理员”,
“支点”:{
"纪律":四,,
“id”:1,
“位置ID”:26
}
}
]
}

这是一个与
locationId 26
相关的所有学科的列表,但是讲师没有被
locationId
过滤-请注意,返回的第一位讲师的
locationId
为27,而不是26。我是否在文档中遗漏了一些明显的内容?如果没有,我如何根据locationId筛选讲师?

在Laravel中,有两个独立的任务由雄辩的构建者执行,他们没有真正意识到彼此,因为他们没有共享相同的查询。 因此,请尝试以下方法:

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

你也试过
wherePivot()
了吗?谢谢@Tanner-我最终在laracasts找到了解决方案,但这是正确的答案