Search code examples
laravelrelationships

Provide extra condition in eager loading which includes comparing of two columns, laravel


I have tables students, profiles, subjects and pivot table profile_subject

-students---------{id,profile_id,year}

-profiles---------{id}

-profile_subject--{profile_id,subject_id,year}

-subjects---------{id}

I want to select a student with id 5, and eager load profile and subjects for the students year.

Something like this:

$student = Student::with('profile','profile.subjects')->find(5);

But I also have to insert the condition

->wherePivot('year','=','students.year')

there somewhere. How to do that? This query will not do the job cos it will search for records which year is "students.year" literary


Solution

  • Use lazy eager loading. This code will not create any additional queries, it'll create the same amount of queries as with() would:

    $student = Student::find(5);
    $sudent->load(['profile', 'profile.subjects' => function ($q) use ($student) {
        $q->wherePivot('year', $student->year);
    }]);