I am trying to eager load some relationships from my user model. The scenario is as follows: A user can have many sales
and each sale can consist of many items
.
I have setup the following relationships in my models:
User Model:
// Attach User Sales
public function sales()
{
return $this->hasMany(\App\Models\Sale::class, 'user_id', 'id');
}
Sale Model:
// Attach Items
public function items()
{
return $this->hasMany(Item::class, 'sale_id', 'id');
}
I can access the user sales by doing the following:
Auth::user()->sales
And i can then loop through these sales to get the corresponding items in the sale, like so:
@foreach(Auth::user()->sales as $sale)
{{ dump($sale) }}
{{ dump($sale->items) }}
@endforeach
However, this then presents me with the N+1
problem.
I was hoping to eager load the nested items
relationship to reduce the query size.
Any help is much appreciated.
Edit
Use Lazy Eager Loading
because user is already fetched. And for nested relations use dot syntax
.
Try this
Auth::user()->load('sales.items');
This will give you nested results to iterate over.
User (object)
|
|_ User Sales (Collection)
|
|_ Items of each sale (Collection)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With