优化 Laravel 中复杂报告系统的 Eloquent 查询

问题描述 投票:0回答:1
  • 我有多个包含数百万条记录的表,并且我当前的 Eloquent 查询面临着性能挑战。

  • 我有三个表=“销售额”、“费用”和“利润”

  • 每个表都有“amount”、“date”和“category_id”等列

  • 我需要生成一份报告,显示每个类别每月的总销售额、总费用和净利润

  • 我目前正在使用 Eloquent 来获取每个类别和月份的数据,但是随着数据的获取,查询变得越来越慢。

// Fetch total sales for a category in a specific month
$sales = Sale::where('category_id', $categoryId)
             ->whereMonth('date', $month)
             ->whereYear('date', $year)
             ->sum('amount');
  • 我可以采用哪些策略来优化 Laravel 中大型数据集的 Eloquent 查询?
  • 为了获得更好的性能,我应该考虑特定的索引技术或缓存机制吗?
  • 是否有更有效的方法来构建数据库或查询来处理此类报告场景?
laravel eloquent database-performance laravel-query-builder
1个回答
0
投票

有很多方法可以提高性能。首先,您可能需要向

category_id
date
amount
列添加索引。其次,您可以采用“分块”。最后,您可以使用缓存优化当前查询。

// Fetch total sales for a category in a specific month
$sales = Cache::remember("sales-$categoryId-$month-$year", 60, function () use ($categoryId, $month, $year) {
    return Sale::where('category_id', $categoryId)
                ->whereMonth('date', $month)
                ->whereYear('date', $year)
                ->sum('amount');
});
这里使用

Cache::remember
方法来缓存查询结果。第一个参数是缓存的唯一键。第二个参数是存储缓存的分钟数。第三个参数是包含查询的闭包。如果缓存不存在,则会执行Closure,并将其结果存储在缓存中..

© www.soinside.com 2019 - 2024. All rights reserved.