简体   繁体   English

渴望加载 3 关系?

[英]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:当我进行查询时,查询中有 n+1,如下所示:

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.这将加载cart关系,然后加载该cartproducts 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).它不会多次运行这些查询,因为此User现在已加载其cart关系(因此当通过动态属性访问时不会再次加载)。 That Cart has its products relationship loaded (which will not be loaded again when accessed via the dynamic property).Cart已加载其products关系(通过动态属性访问时不会再次加载)。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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