Laravel carbon 获取特定月份值的总和

Laravel carbon get sum of particular month values

我有一个 table 列 - 启动、停止、机械、labor_hrs。基本上它记录了机械师在工作中的时间。 我试图在我的模板中显示每个机械师每月的总小时数。

控制器:

public function index()
{

    $subith = Laborhrs::all()->where('mechanic','7');
    return view('reports.labour_monthly')->with('subith',$subith);
}

模板:

    @foreach($subith as $subith)
    <tr>
        <td>{{\Carbon\Carbon::parse($subith->stop)->format('M')}}</td>
        <td>{{$subith->labor_hrs}}</td>
    </tr>
    @endforeach

我得到这样的结果:

我需要得到它 - 这名员工的 9 月总计和 10 月的总计。我错过了什么?

选项 1:在查询中分组

控制器:

public function index()
{
    $subiths = Laborhrs::selectRaw('MONTH(stop) as month, sum(labor_hrs) as sum')
        ->where('mechanic', 7)
        ->groupBy('month')
        ->orderByDesc('stop')
        ->get();

    return view('reports.labour_monthly', compact('subiths'));
}

查看:

@foreach($subiths as $subith)
    <tr>
        <td>{{ date("F", mktime(0, 0, 0, $subith->month, 1)) }}</td>
        <td>{{ $subith->sum }}</td>
    </tr>
@endforeach

方案二:分组查询结果

如果每个机制的数据很多,请不要使用此选项。

控制器:

public function index()
{
    $subiths = Laborhrs as sum')::where('mechanic', 7)
        ->orderByDesc('stop')
        ->get();

    $grouped = $subiths->groupBy(function($item){
       return \Carbon\Carbon::parse($item->stop)->format('F');
    });

    return view('reports.labour_monthly', compact('grouped'));
}

查看:

@foreach($grouped as $month => $group)
    <tr>
        <td>{{ $month }}</td>
        <td>{{ $group->sum('labor_hrs') }}</td>
    </tr>
@endforeach