[英]Get datas from relation table (with()) with a condition
I have an 'implementation' table that contains relationships to retrieve projects
and scores
. 我有一个“实现”表,其中包含检索
projects
和scores
关系。
The scores
table contains a" user_id "field. scores
表包含一个“ user_id”字段。
I would like to collect all the implementations but with only the score
which contains the user_id. 我想收集所有实现,但只包含包含user_id的
score
。
My original query. 我的原始查询。
public function getImplementations($id, $student)
{
$data = Implementation::where('event_id', $id)->where('student_id', $student)->with('project', 'score')->get();
return response()->json($data);
}
My test for get only the score from specific user (only one score per user per implementation, so no conflict possible) 我的测试仅从特定用户获得分数(每个实现每个用户只有一个分数,因此不可能发生冲突)
$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();
But that does not give the expected result. 但这并不能给出预期的结果。 This is not the right method and I do not know the right one.
这不是正确的方法,我也不知道正确的方法。
Thanks for your help 谢谢你的帮助
I am not sure if there's a need to eager-load and constrain a relationship simultaneously. 我不确定是否需要同时渴望和约束一个关系。 Does the following provide you with the expected result?
以下内容是否能为您带来预期的结果?
$data = Implementation::where('event_id', $id)
->with([
'project',
'score' => function ($query) {
$query->where('user_id', Auth::id());
}
])
->where('student_id', $student)
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.