DawgOnKing
6 months ago
110
15
Eloquent

Eager Load vs Model->relationship

Posted 6 months ago by DawgOnKing

Consider a Post with 10 Comments

OPTION A (EAGER LOADING)

//controller
$post->with('comments')->find($post->id);

//blade
@foreach($post->comments as $comment)
    {{ $comment->body }}
@endforeach

select
  *
from
  `comments`
where
  `comments`.`commentable_id` in (1)
  and `comments`.`commentable_type` = "App\Post"

//duration 0.41ms

OPTION B

//controller
compact('post');

//blade
@foreach($post->comments as $comment)
    {{ $comment->body }}
@endforeach

select
  *
from
  `comments`
where
  `comments`.`commentable_id` = 1
  and `comments`.`commentable_id` is not null
  and `comments`.`commentable_type` = "App\Post"

//duration 0.39ms

Both run identical query count.

Is there a significant advantage to eager loading as the application scales?

Are these examples essentially identical as they appear to be?

Am I correct is assuming is all comes down to page render with regards to load time between the options? Essentially, eager loaded data is available immediately at page render while second option has to actually perform query and get results before page will render, etc....

Please sign in or create an account to participate in this conversation.