Laravel Classroom image

osdyui
 
To post your Question Join Classroom
 
Lesson Topics's No:-  First|1 | 2 | 3 | 4 | 5 | 6|Last
Lessons:-Eloquent ORM

11.5 Eager Loading
Eloquent gives the option of Eager Loading to help solve the highly debated N+1 issue. If you
don’t know what this is, let me break it down for you using what we have already learned. Take
a look at the following snippet of code.
1 <?php
2
3 $users = User::all();
4
5 foreach ($users as $user)
6 {
7 echo $user->hat->size();
8 }
For every loop iteration, Eloquent has to perform another SQL query to retrieve that users Hat
object and find its size. Now this isn’t going to be a huge problem on small data sets, but with
hundreds of rows it could drastically affect performance. With eager loading we can tell Eloquent
to run a SELECT * FROM hats; when retrieving the User object so that we already have all the
data we need. This reduces the amount of strain to only two SQL queries. Much better!
Let’s see how we can tell Eloquent to eager load a relation:
1 <?php
2
3 $users = User::with('hat')->get();
There, now the hat relationship is eager loaded. If we want to eager load several relationships,
simply pass an array to the with() method. It’s worth noting that the with() method is static
and as such must always be at the start of the chain.
You can even eager load nested relationships. Let’s assume that our Hat object has a hatstand()
relationship to let us know which stand it’s on. We can eager load both of the relationships like
this.
1 <?php
2
3 $users = User::with(array('hat', 'hat.hatstand'))->get();
Simply prefix the relationship name with the nested object.
What if we want to add some conditions to our eager loading? Maybe we are only going to be
using blue hats? Of course we can do this with Eloquent! Simply pass the relationship name as
a key to the array, and a closure containing conditions as a parameter. This is better explained
through code.1 <?php
2
3 $users = User::with(array('hat' => function($query) {
4 $query->where('color', '=', 'blue');
5 }))->get();
Simple. You can add as many queries as you need to!

 

 
 
 

osdyui

Skills    Laravel

Qualifications :-
Location :-,,,
Description:-
Explore
 

  Students (0)