Laravel:在有多个预加载查询时提高性能

Laravel: improve performance when having multiple eager loading queries

我正在尝试提高 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 次),因为每次都会再次查询关系。这些查询是否可以合并为 7 个查询而不是 15 个?

由于不同的集合应该通过引用传递,您应该能够将它们组合成一个 Eloquent 集合,然后使用 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 个关系查询。