我有一个名为 maintenance
的数据库,其中有一个名为 cost
的字段。我现在想按 month 和year
获取成本总和,并按 month 和year
按降序排列。有人可以帮我吗?
这是我尝试过的
$MaintenanceStats = Maintenance::oldest() ->get() ->groupBy(function($val) { return Carbon::parse($val->from)->format('F'); }) ->take(7);
我得到了下面这个集合对象,它工作得很好。但是我如何才能按月和年对它们进行分组,然后按降序排列它们,而不仅仅是按月分组呢?另外,我只需要每月的总费用;我不需要所有维护记录。
Illuminate\Database\Eloquent\Collection {#1517 ▼ // app\Http\Controllers\GeneralController.php:40 #items: array:5 [▼ "September" => Illuminate\Database\Eloquent\Collection {#1452 ▶} "July" => Illuminate\Database\Eloquent\Collection {#1530 ▶} "January" => Illuminate\Database\Eloquent\Collection {#1519 ▶} "November" => Illuminate\Database\Eloquent\Collection {#1520 ▶} "December" => Illuminate\Database\Eloquent\Collection {#1521 ▶} ] #escapeWhenCastingToString: false }
P粉5614384072024-03-29 11:08:04
最好的方法是使用数据库查询来完成此操作,但您还需要一个原始查询:
$maintenanceStats = Maintenance::selectRaw("year(`from`) AS year, month(`from`) AS month, sum(cost) AS cost_total") ->groupByRaw("year(`from`)") ->groupByRaw("month(`from`)") ->orderBy('year') ->orderBy('month') ->get();