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

Laravel Livewire:如何将学生多行考勤数据合并为单行展示

解决方案

要实现每个学生一行展示考勤数据,可以通过Laravel集合的分组和映射功能来处理,步骤如下:

1. 修改Livewire控制器中的查询逻辑

将原有的Attendance::get()替换为集合分组处理的代码,把相同学生的考勤记录合并,并整理日期与考勤状态的对应关系:

$this->StudenAttendance = Attendance::get()
    // 按student_id分组,聚合同一学生的所有考勤记录
    ->groupBy('student_id')
    // 处理每个学生的分组数据
    ->map(function ($attendanceGroup) {
        // 获取学生的基础信息(取分组内第一条记录即可)
        $baseInfo = $attendanceGroup->first();
        // 将考勤记录转换为「日期 => 考勤状态」的关联数组
        $attendanceMap = $attendanceGroup->pluck('attendance', 'date_of_attendance');
        
        return [
            'name' => $baseInfo->name,
            'student_id' => $baseInfo->student_id,
            'attendances' => $attendanceMap
        ];
    })
    // 重置集合索引,避免以student_id作为键
    ->values();

2. 在Livewire视图中渲染合并后的数据

视图里需要动态生成日期表头,并对应展示每个学生的每日考勤状态:

<table border="1" cellpadding="8">
    <thead>
        <tr>
            <th>姓名</th>
            <th>学生ID</th>
            {{-- 提取所有唯一日期作为表头 --}}
            @foreach($StudenAttendance->pluck('attendances')->flatten()->keys()->unique() as $date)
                <th>{{ $date }}</th>
            @endforeach
        </tr>
    </thead>
    <tbody>
        @foreach($StudenAttendance as $student)
            <tr>
                <td>{{ $student['name'] }}</td>
                <td>{{ $student['student_id'] }}</td>
                {{-- 遍历所有日期,展示对应考勤状态,无数据则显示占位符 --}}
                @foreach($StudenAttendance->pluck('attendances')->flatten()->keys()->unique() as $date)
                    <td>{{ $student['attendances'][$date] ?? '-' }}</td>
                @endforeach
            </tr>
        @endforeach
    </tbody>
</table>

说明

  • groupBy('student_id'):将同一学生的所有考勤记录聚合为一个子集合
  • pluck('attendance', 'date_of_attendance'):快速构建日期与考勤状态的映射关系,方便后续按日期取值
  • 视图中动态生成表头:确保所有出现过的考勤日期都能作为列展示,适配数据的扩展性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 10:51:23