I'm learning Laravel, and I'm using Laravel 5.2. I want to know about Eager Loading, Constraining Eager Loads, and Lazy Eager Loading. What are the similarities and differences between those three? Can you give an example for each of them? I have read Laravel documentation, but I still don't understand. I hope you can give clearer explanation. Thanks.
1条回答 默认 最新
douyan6871 2016-10-22 12:19关注Nutshell:
Eager Loadingallows you to get the relationships for some Models efficiently.Constraining Eager LoadsAgain makes it efficient but you can limit your results e.g. date range, specific id etcLazy Eager LoadingIs for when you already have your parent models loadedExample:
Ok, lets say you're making a Blog where you will have Posts and those post can have comments and likes.
Scenario 1:
You want to get all the
Postswith theirCommentsand theirLikes. Would you load all thePosstand then loop through them and get therecommentsandlikes? Well, you could but this could end up being very expensive as it could end up performing many, many queries. Or you could load the posts and then get theirids and load all the comments that you need for thoseids and the same for there likes as well. This is essentially whatLaraveldoes with eager loading.Scenario 2 (a real world example of Scenario 1):
You're creating you feed for the posts. So, you've loaded up all your Posts and then you want to show how many likes and comments it has so you would have something like (very basic):
Controller:
$posts = App\Post::all(); return view('posts.index', compact('posts'));blade file:
@foreach($posts as $post) <h2>{{ $post->title }}</h2> <p>{{ $post->description }}</p> <p> Likes: {{ $post->likes->count() }} <br> Comments: {{ $post->comments->count() }} </p> @endforeachThe above would work but for every loop it would actually be querying the database. Changing your controller to:
$posts = App\Post::with('likes', 'comments')->get(); return view('posts.index', compact('posts'));Will then get the
commentsandlikesfor all of thePostsbeforehand saving the database and making your application much more efficient.Scenario 3
I want to show the
Postsbut I only want to show the last 3commentsthat were made.$posts = App\Post::with(['comments' => function ($query) { $query->limit(3); }]);Lazy Eager Loadingis for when you've already loaded yourPostsand you then need to get all thecommentsorlikesafter the fact. Same principle but you would useloadinstead ofwith. Another reason you might use load is if you usingRoute model bindingfor your controllers so thePostwill have already been retrieved but you still want to get it's relationships.Hope this help!
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报