簡體   English   中英

Laravel組按月求和總計

[英]Laravel groupBy month and sum the total

數據結構

[
{
  "id": "1",
  "date": "2019-06-22",
  "total": "1200" // THIS TOTAL IS A MUTATOR
},
{
  "id": "2",
  "date": "2019-06-24",
  "total": "2200" // THIS TOTAL IS A MUTATOR
},
{
  "id": "3",
  "date": "2019-07-20",
  "total": "2300" // THIS TOTAL IS A MUTATOR
},
]

我正在嘗試做的是:

我想將這些數據按MONTH分組並返回總和

預期結果:

2019-06總數為1200 AND 2019-07總數為4500

我試過的

$customer_branch = ExportInvoice::where('customer_branch_id', $customer_branch_id)
            -> approved()
            -> whereYear('date', $year)
            -> orderBy('date', 'ASC')
            -> get();

而且我嘗試循環拋出$customer_branch並將數據設置為數組,但是沒有得到預期的結果

1.打開config/database.php

2.在mysql連接設置里面找到strict密鑰

3.將值設置為false

4.然后運行php artisan config:cache

現在嘗試此查詢

ExportInvoice::select('id',\DB::raw('SUM(total) as total,DATE_FORMAT(date,"%Y-%m") as monthDate'))
->where('customer_branch_id', $customer_branch_id)
->approved()
->groupBy(\DB::raw('DATE_FORMAT(date,"%Y-%m")'))
->orderBy('date')
->get();

groupBy中的Simble DB:raw應該可以解決問題。

$customer_branch = ExportInvoice::where('customer_branch_id', $customer_branch_id)
   ->approved()
   ->whereYear('date', $year)
   ->groupBy(DB::raw(DATE_FORMAT(date,'%Y-%m'))
   ->get();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM