Reputation:
I have these tables:
users | name - ...
carts | user_id - ...
cart_product | cart_id - product_id
relations:
Cart model
public function products()
{
return $this->belongsToMany(Product::class)
->withPivot('quantity','coupon_id')
->withTimestamps();
}
User model:
public function cart()
{
return $this->hasOne(Cart::class);
}
when i do the query there is n+1 in query like so:
auth()->user()->cart()->with('products')->products
How can I eager loading the query??
Upvotes: 1
Views: 107
Reputation: 50561
I assume you just want the products?
$products = auth()->user()->cart->products;
This will load the cart
relationship then the products
for that Cart. It will not run these queries more than once, as this User
now has its cart
relationship loaded (so it won't be loaded again when accessed via the dynamic property). That Cart
has its products
relationship loaded (which will not be loaded again when accessed via the dynamic property).
If you really feel like you want to "Lazy Load" these relationships (which you would have to see if the query is any different as it should just be the same as accessing it via the dynamic property) you can do that:
$products = auth()->user()->load('cart.products')->cart->products;
Upvotes: 2