简体   繁体   English

Laravel foreach 中的重复查询

[英]Laravel Duplicated queries in foreach

hey everyone I'm trying to make my laravel app faster and what I see in debug bar is so many duplicated queries嘿大家我正在努力让我的 laravel 应用程序更快,我在调试栏中看到的是很多重复的查询在此处输入图像描述

and why this happens?为什么会这样? because I'm calculating discount in the product model and when I'm getting products in my foreach I use $product->discount() and let's see what's happening in the Product model and discount function, there it is因为我正在计算产品 model 的折扣,当我在我的 foreach 中获取产品时,我使用 $product->discount(),让我们看看产品 model 和折扣 ZC1C425268E68385D1AB450 中发生了什么,

public function discount(){
        $seller = ProductSeller::orderBy('price','asc')-where('product_id',$this->id)->first();
        $sellerDiscount = Discount::where('seller_id',$seller->seller_id)-latest('created_at')->first();
        $brandDiscount = Discount::where('brand_id',$this->brand_id)-latest('created_at')->first();
        $categoryDiscount = Discount::whereIn('category_id',$cateName)-latest('created_at')->first();
} 

these are the queries that are duplicating in my category pages in a foreach any idea to prevent the duplicating of each query?这些是在 foreach 中我的类别页面中重复的查询有什么想法可以防止每个查询的重复吗?

Yes it happens, because you are calling function( $product->discount() ) instead of getting data from that.是的,它发生了,因为您正在调用函数( $product->discount() )而不是从中获取数据。 Try to use eager load to fix this.尝试使用急切的负载来解决这个问题。

And then get data like this,然后得到这样的数据,

$product->seller

You can do this from Your main query and put condition in that.您可以从您的主查询中执行此操作并将条件放入其中。

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

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