N+1 query problem
Interview answer
N+1 occurs when one query retrieves the parent records and then one additional query runs for each parent.
$users = User::all();
foreach ($users as $user) {
echo $user->orders->count();
}
If there are 1,000 users, this can result in roughly:
1 query for users
+ 1,000 queries for orders
= 1,001 queries
Fix:
$users = User::with('orders')->get();
For large datasets, I also consider whether I actually need the complete relationship data.
For example:
$users = User::withCount('orders')->get();
Then:
$user->orders_count;
may be much cheaper than loading every order.
0 comments:
Post a Comment
Thanks