使用条件

时间:2019-01-21 19:52:01

标签: php laravel eloquent

我有一个“实现”表,其中包含检索projectsscores的关系。

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();

但是,这不能给出预期的结果。这不是正确的方法,我也不知道正确的方法。

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

我不确定是否需要同时渴望和约束一个关系。以下内容能为您带来预期的结果吗?

$data = Implementation::where('event_id', $id)
    ->with([
        'project',
        'score' => function ($query) {
            $query->where('user_id', Auth::id());
        }
    ])
    ->where('student_id', $student)
    ->get();