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
}
>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 ofUserfor 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 ofComment, loop over the collection and assign every comment to the proper User -
Return the collection of Users