Use Eager Loading to reduce query sent
Often we heard about eager loading and lazy loading . What are the difference between them ?
Well, let’s look at the explanation retrieved from Tutorialspoint:
Eager loading : Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query.
Lazy loading: Lazy loading is the opposite of Eager loading. It delay the loading of related data, until you specifically request for it.
Below is an example of lazy loading by using Laravel eloquent.
$customers= App\Customer::all();foreach ($customers as $customer) {
echo $customer->order->status;
}
Let’s say there are 10 different customers and each customer has one order. There will be 1 query sending to the database to retrieve the customers information and another 10 query send to the orders tables to retrieve the order status. In total, there would be 11 queries sending to the database to retrieve these information.
Query sent to DB:
select * from customers select * from orders where customer_id = 1 select * from orders where customer_id = 2 select * from orders where customer_id = 3 //so on till customer_id = 10
Below is an example of lazy loading by using Eager eloquent.
$customers= App\Customer::with('order')->get();foreach ($customers as $customer) {
echo $customer->order->status;
}
These only result in 2 queries. One to retrieve the customers data and another one to retrieve the data from the order table. As it has loads the related entities as part of the query in when we declare $customers.
By using eager loading, we can reduce the number of queries from 11 to 2 . This does help to save the query that the database has to execute .As there are only 2 queries to execute in the database.
Query sent to DB :
select * from customers select * from orders where customer_id in (1,2,3,4,5,6,7,8,9,10)
There are few things to take note when using eager loading
- Use eager loading when the model relation is not too complicated.
- Use eager loading when you are sure the related entities will be used.
Hope you like my explanation.
Click the claps if you like it , thanks for reading. :)