我有多个包含数百万条记录的表,并且我当前的 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');
有很多方法可以提高性能。首先,您可能需要向
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,并将其结果存储在缓存中..