Laravel:在执行多个紧急加载查询时提高性能

时间:2019-04-10 11:04:35

标签: laravel performance eloquent eager-loading

我正在尝试提高laravel应用程序的性能。通过消除视图中的延迟加载,我已经能够将查询数量从68个减少到20个。

但是,使用紧急加载,仍然有20个查询几乎可以完成相同的操作。我的代码如下:

$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个),因为每次关系也将再次被查询。可以将这些查询合并为一个查询,而不是15个吗?

1 个答案:

答案 0 :(得分:1)

由于应该通过引用传递不同的集合,因此您应该能够将它们组合成一个单独的口才集合,然后使用Lazy Eager Loading

$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.

$products数组中的原始集合现在应该已经加载了所有关系,但是应该只执行了4个查询,而不是12个查询。