Search code examples
phpeloquentlaravel-5.6eager-loadinglaravel-5.7

How can I eager load on 3 different relationships in Laravel?


I have 4 tables: user, user_course, classes, and queues.

user_course has a user_id, classes has a user_course_id, and queues has a classes_id column.

I'd like to retrieve all queues with a class_id that corresponds to a user_course registered by the current user_id.

Basically, what I want to do is: $user->user_course->classes->queues

Except I can't loop over the above directly.

So how can I eager load it with something like $classes = App\Classes::with('Queues') except constrain it to the currently logged in user_id?

I'm new to eager loading and can't get this to work. Please inform me if I need to edit my question details.


Solution

  • You can use:

    $user = User::with('user_course.classes.queues')->find($idOfUser);
    

    It will first run query to get user courses, then it will run query to get user courses classes and then it will run query the get queues of classes.