问题描述
我有桌子 absentee_record
来自数据库的虚拟记录
id | student_id | 注意 | from_date | 至今 |
---|---|---|---|---|
1 | 1 | 离开 | 2021-06-06 | 2021-06-10 |
我想为每个日期获取 absentee_records
。就像每个日期会有 5 行。
控制器
$from_date = $request->input('from_date');
$to_date = $request->input('to_date');
$student_ids = [];
foreach($students as $student) {
$student_ids[] = $student->id;
}
$absentees = AbsenteeRecord::whereIn('student_id',$student_ids)->whereDate('from_date','>=',$from_date)->whereDate('to_date','<=',$to_date)->get();
<table class="table" width="100%">
<thead>
<tr>
<th>Date</th>
<th>Name</th>
<th>Note</th>
</tr>
</thead>
<tbody>
@foreach ($absentees as $absentee)
<tr>
<td>{{ $absentee->date ?? '' }}</td>
<td>{{ $absentee->student->full_name ?? '' }}</td>
<td>{{ $absentee->note ?? '' }}</td>
</tr>
@endforeach
</tbody>
</table>
日期 | 姓名 | 注意 |
---|---|---|
2021-06-06 | 约翰 | 离开 |
2021-06-07 | 约翰 | 离开 |
2021-06-08 | 约翰 | 离开 |
2021-06-09 | 约翰 | 离开 |
2021-06-10 | 约翰 | 离开 |
解决方法
- 你不能只使用 SQL 来做到这一点,因为根据你的表模式,每个学生在不同的日子只有一行。
- 您可以使用 PHP 代码构建您想要的结构,如下所示。
@foreach ($absentees as $absentee)
@if ($absentee->to_date > $absentee->from_date)
/* some code here to loop date from from_date to to_date */
@else
<tr>
<td>{{ $absentee->date ?? '' }}</td>
<td>{{ $absentee->student->full_name ?? '' }}</td>
<td>{{ $absentee->note ?? '' }}</td>
</tr>
@endif
@endforeach