我有两个表的用户和出勤率。
在出勤表中,包含present_date
和present_type
明智的用户出勤率。
present_type
将保留以进行移位。如果轮班,则用户可能有多个出席日期。
因此,一个用户在出勤表中可能有很多行。
我想向所有用户展示
已选中=>如果发现特定日期的出勤率和用户类型
unchecked =>如果while循环视图中当天不存在出勤。
$userList = User::
orWhereHas('userAttendance', function ($q) use ($attDate,$type) {
$q->where('present_date', $attDate);
$q->wherePresentType($type);
})->get();
在刀片文件循环中:
@foreach($userList as $key => $user)
<input value="{{$user->id}}" title="" type="checkbox"
@if($user->userAttendance)
checked="checked" data-exist-id="{{$user->userAttendance->id}}"
@endif class="action-normal" />
但这不能按预期工作。
它可以检查出勤表上是否存在行,而没有过滤日期或orWhereHas
声明中写的类型!
我想检查出勤表上是否存在特定日期的数据(如果present_type用于不上班),而无需再次查询以保持有限的数据库命中率。
我可以通过在用户模型中创建一个函数来执行此操作,该函数在循环时从刀片文件获取参数。但是我不想做额外的数据库查询。
有什么办法可以使用纯粹的口才吗? 我可以在循环时使用控制器功能发送的数据为用户检查它吗?
答案 0 :(得分:1)
为什么或在哪里?
尝试一下:
$userList = User::query()
->with(['userAttendance' => function($q) use($attDate,$type) {
$q->where('present_date', $attDate);
$q->wherePresentType($type);
}])
->get();
最好加载关系,以避免在视图中出现多个查询。
编辑:这将为您提供所有用户并在条件满足时加载正确的userAttendance关系。