简体   繁体   中英

Get datas from relation table (with()) with a condition

I have an 'implementation' table that contains relationships to retrieve projects and scores .

The scores table contains a" user_id "field.

I would like to collect all the implementations but with only the score which contains the user_id.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM