首頁  >  問答  >  主體

如何解決Laravel中的group by和order by問題?

我有一個名為 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粉823268006P粉823268006178 天前382

全部回覆(1)我來回復

  • P粉561438407

    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();

    回覆
    0
  • 取消回覆