Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eager loading nested relationships on the Auth::user() facade

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.

like image 581
Josh Bolton Avatar asked Aug 02 '17 15:08

Josh Bolton


1 Answers

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)
like image 61
Zayn Ali Avatar answered Nov 13 '22 21:11

Zayn Ali