Php laravel慢速查询问题优化
我想优化我的查询,因为它需要很长时间来运行与当前的雄辩。我有两张桌子,玩具和产品。 从每个产品中保留一个作为玩具样本,如果没有,则必须通过查询将其更新为样本,因此我现在正在做的事情如下Php laravel慢速查询问题优化,php,laravel,Php,Laravel,我想优化我的查询,因为它需要很长时间来运行与当前的雄辩。我有两张桌子,玩具和产品。 从每个产品中保留一个作为玩具样本,如果没有,则必须通过查询将其更新为样本,因此我现在正在做的事情如下 $toywithsample=product::select('toyid')->groupBy('toyid')->where('sample','yes')->get(); 上面的代码是为了获取所有产品的id,这些产品在其产品中有一个示例 $toywithoutsamples=toy::s
$toywithsample=product::select('toyid')->groupBy('toyid')->where('sample','yes')->get();
上面的代码是为了获取所有产品的id,这些产品在其产品中有一个示例
$toywithoutsamples=toy::select('id')->whereNotIn('id',$toywithsample)->get();
上面的代码是为了获得所有产品的id,这些产品中没有样品玩具
foreach($toywithoutsamples as $toywithoutsample){
$product=product::where('toyid',$toywithoutsample->id)
->where('sample','sale')->limit(1)
->update(['sample'=>'yes']);
}
以下是表格结构
玩具桌
身份证,姓名
产品
id,toyid,样本
$toys_ids_with_sample = Product::where('sample', 'yes')->get()->pluck('toyId');
// get the products grouped by toyId.
$products = Product::whereNotIn('toyId', $toys_ids_with_sample)->where('sample', 'sale')->get()->groupBy('toyId');
// get the product ids whose sample field you want to change to
// yes.
$update_product_ids = [];
foreach($products as $toyId => $products){
// We will only pick the first one, as we have to change just 1.
array_push($update_product_ids, $products->first()->id);
}
Product::whereIn('id', $update_product_ids)->update(['sample' => 'yes']);
这减少了查询的总数。您应该定义两者之间的关系,并使用适当的Laravel命名约定,这样您就可以简单地通过关系进行查询,然后您可能只需批量更新,而不是单独查询。基本上,您可以将这3个查询(其中一个在循环中,通常设计得很糟糕)转换为一个或两个查询。