Learn How to Use Eager Loading
HTML-код
- Опубликовано: 11 июл 2024
- Using eager loading in Laravel can improve application performance significantly. Learn how to use eager loading and what eager loading is.
We start with over 4000 queries to load 1000 tickets and take the query count to 6. Not only does the query count reduce, but the memory and load time decrease significantly as well.
This will be an iterative approach to show the power of eager loading your relationships.
Thank you for watching. Like and sub if this video was helpful.
~~~~~
Follow me on Twitter
/ nick_escobedo
~~~~~
#php #laravel #eagerloading Наука
A couple of extra points here.
for the comments count, it's better to use the ->withCount() method, in this example ->withCount(['comments']) and then using the $ticket->comments_count in the blade view file - this has benefit of doing a count query for you during the load of the ticket itself AND it doesn't need to load/hydrate the collection of comments.
secondly for the comment author name, this can/should be added as a separate relationship
public function firstComment(): HasOne
{
return $this->hasOne(Comment::class)->oldest('created_at');
}
and then you can eager Load the 'first_comment.author' - reducing the size of the data and query down directly to just 1 comment.
These are great points, thanks for mentioning them!
Very useful. Would you mind sharing a link to this repo or just the factory and seeder files so we can play around?
thanks for your hard working🤩
Thank you for the kind words :)