简体   繁体   中英

Eager loading 3 relationships?

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??

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM