You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 如何查询考勤表并按staff_id分组合并上下班打卡两行记录

问题背景

我想要实现如下表格效果:
目标表格

我当前的表格效果如下:
当前表格


数据表说明

打卡类型type字段规则:0代表上班打卡(Time in),1代表下班打卡(Time out)

  • MySQL attendance考勤表展示:
    考勤表展示1
  • MySQL attendance考勤表详情:
    MySQL考勤表详情
  • MySQL Staff员工表:
    员工表

现有代码

Dashboard Controller 代码

public function index()
{
    $data = [
        'attendances'=>Attendance::query()
            ->where('type','!=','255')
            ->with('staff')->get()
    ];

    return view('dashboard.attendance_table',$data);

//    $attendances = Attendance::all(); // or whatever Eloquent query you want that returns a collection
//
//    $grouped = $attendances->groupBy('staff_id');
//
//    dd($grouped);
}

attendance.blade 视图代码

<div class="row">
    <div class="col-lg-12">
        <div class="card overflow-hidden">
            <div class="card-body">
                <div>
                    <h6 class="main-content-label mb-1">Attendance Table</h6>
                </div>
                <div class="table-responsive">
                    <table id="exportexampl" class="table table-bordered border-t0 key-buttons text-nowrap w-100 display" >
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Staff Name</th>
                                <th>User ID</th>
                                <th>Time In/ Time Out</th>
                                <th>Card No.</th>
                                <th>Date</th>
                                <th>Time</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($attendances as $attendance)
                            <tr>
                                <td>{{$loop->iteration}}</td>
                                <td>{{ $attendance->staff->name }}</td>
                                <td>{{ $attendance->staff->userid }}</td>
                                {{-- <td>{{gettype($attendance->type)}}</td> --}}
                                <td>{{ ($attendance->type==0) ? 'Time in': 'Time out'}}</td>
                                <td>{{ $attendance->staff->cardno }}</td>
                                <td>{{ \Carbon\Carbon::parse($attendance->timestamp)->toDateString() }}</td>
                                <td>{{ \Carbon\Carbon::parse($attendance->timestamp)->format("H:i:s") }}</td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

具体问题

我要如何对当前的考勤表查询结果进行分组,才能实现上述目标考勤表的效果?


内容的提问来源于stack exchange,提问作者Wanjila Abraham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 09:24:07