Laravel:在有多个急切加载查询时提高性能
我正在努力提高我的laravel应用程序的性能。通过删除视图中的延迟加载,我已经能够将查询量从68个减少到20个 然而,使用即时加载,仍然有20个查询执行几乎相同的操作。我的代码如下所示:Laravel:在有多个急切加载查询时提高性能,laravel,performance,eloquent,eager-loading,Laravel,Performance,Eloquent,Eager Loading,我正在努力提高我的laravel应用程序的性能。通过删除视图中的延迟加载,我已经能够将查询量从68个减少到20个 然而,使用即时加载,仍然有20个查询执行几乎相同的操作。我的代码如下所示: $products = [ 'latest' => Product::with('vehicle', 'brand', 'type', 'photos')->withoutGlobalScope(ProductScope::class)->latest()->take(
$products = [
'latest' => Product::with('vehicle', 'brand', 'type', 'photos')->withoutGlobalScope(ProductScope::class)->latest()->take(5)->get(),
'most_viewed' => Product::with('vehicle', 'brand', 'type', 'photos')->withoutGlobalScope(ProductScope::class)->mostViewed()->take(5)->get(),
'nearest' => Product::with('vehicle', 'brand', 'type', 'photos')->withoutGlobalScope(ProductScope::class)->nearest($address)->take(5)->get(),
];
这将导致15个查询(每个查询5个),因为每次都会再次查询关系。这些查询是否可以合并为7个查询而不是15个查询?因为不同的集合应该通过引用传递,所以您应该能够将它们合并到一个有说服力的集合中,然后使用:
$products
数组中的原始集合现在应该加载了所有关系,但它应该只执行了4次查询,而不是12次查询关系。您使用的是什么版本的Laravel?抱歉,忘了提及,我使用的是Laravel 5.8您的解决方案部分有效。我可以看到查询的数量减少了。但是,如果同一个产品出现在多个集合中,则只有最后一个产品具有这种关系。@Lextewilligen啊,是的,merge
使用模型中的键,因此它只将其中一个加载到集合中。我更新了我的答案,应该给你你想要的。嗯,你又对了一半。但是,由于某种原因,所有型号都加载得很好,查看次数最多的
和最近的
中的项目也添加到了最新的
。如果我更改了顺序,这些项将被推送到第一个$products数组项。@LexdeWilligen我已更新了我的答案,以便只使用一个新的雄辩的集合实例来解决最后一个问题。
$products = [
'latest' => Product::withoutGlobalScope(ProductScope::class)->latest()->take(5)->get(),
'most_viewed' => Product::withoutGlobalScope(ProductScope::class)->mostViewed()->take(5)->get(),
'nearest' => Product::withoutGlobalScope(ProductScope::class)->nearest($address)->take(5)->get(),
];
//Merge the different Product collections into one for the lazy eager loading
$collection = new \Illuminate\Database\Eloquent\Collection();
foreach ($products as $items) {
foreach ($items as $model) {
$collection->push($model);
}
}
$collection->load('vehicle', 'brand', 'type', 'photos');
//$products should now contain the different collections but with the additional relationships.