我有一个“实现”表,其中包含检索projects
和scores
的关系。
scores
表包含一个“ user_id”字段。
我想收集所有实现,但只包含score
,其中包含user_id。
我的原始查询。
public function getImplementations($id, $student)
{
$data = Implementation::where('event_id', $id)->where('student_id', $student)->with('project', 'score')->get();
return response()->json($data);
}
我的测试仅从特定用户获得分数(每次实施每个用户仅获得一个分数,因此不可能发生冲突)
$data = Implementation::where('event_id', $id)
->where('student_id', $student)->with('project', 'score')
->whereHas('score', function ($query) {
$query->where('user_id', Auth::user()->id);
})->get();
但是,这不能给出预期的结果。这不是正确的方法,我也不知道正确的方法。
感谢您的帮助
答案 0 :(得分:2)
我不确定是否需要同时渴望和约束一个关系。以下内容能为您带来预期的结果吗?
$data = Implementation::where('event_id', $id)
->with([
'project',
'score' => function ($query) {
$query->where('user_id', Auth::id());
}
])
->where('student_id', $student)
->get();