Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How Laravel loads relations?

Let’s say we do this
$users = User::with('comments')->get();
it will execute

select * from `users`
select * from `comments` where `comments`.`user_id` in (1, 2, 3, 4, 5)

I don’t understand how Laravel knows which comments are linked to which user? Does Laravel do some extra code after it executes queries to link each user to his comments so when we do:

foreach ($users as $user) {
    $user->comments //Laravel knows that which comments to load for this user
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I don’t understand how Laravel knows which comments are linked to which user

Well, in your example every comment has a user_id field, it is not hard to loop over the comments and assign every one to the correct user.

Does Laravel do some extra code after it executes queries to link each user to his comments

Definitely. You should take a deep dive on laravel internals (https://github.com/laravel/framework/) to find the exact parsing code though.

I guess that logically it does something along the lines of:

  • Perform the base query (select * from users), creates a collection of User for each row returned

  • Get the unique user IDS in the collection

  • Perform the relationship query (select * from comments where comments.user_id in (1, 2, 3, 4, 5)), creates a collection of Comment, loop over the collection and assign every comment to the proper User

  • Return the collection of Users

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading