如何解决有没有办法将 2 个 foreach 和一个 for 循环一起循环?
我正在从事 Laravel 8 项目,我将在其中创建人力资源管理系统,所以我现在正在努力报告员工出勤情况。
我有2个模型
User.PHP
和 Attendance.PHP
也是 2 个控制器和模型之间的关系。
public function attendances()
{
return $this->hasMany(Attendance::class,'user_id');
}
这是来自我的AttendanceController.PHP
public function index()
{
return view('frontend.attendances.index',[
'employees' => $this->userRepository->getAllUsers()
->with(['attendances' => function($query) {
$query->where('company_id',Auth::user()->company_id);
}])
->get()
]);
}
所以现在我必须显示包含当月所有日期的表格,并显示每个用户是否在工作。
我有这是我的summary.blade.PHP
@foreach($employees as $employee)
<tr>
<td>
<img class="img-fluid rounded-circle mr-2" width="30" height="30" src="{{ $employee->image ? $employee->image : asset('assets/images/user.jpg') }}" alt="{{ $employee->firstname }}" data-original-title="{{ $employee->firstname }}">
{{ $employee->name() }}
</td>
@PHP($count=0)
@for($i=1; Carbon\Carbon::Now()->daysInMonth >= $i; $i++)
@foreach($employee->attendances as $attendance)
@if($i == Carbon\Carbon::createFromFormat('Y-m-d H:m:s',$attendance->check_in)->isoFormat('D'))
<td class="text-center"><i class="fa fa-check text-success"></i></td>
@PHP($count++)
@else
<td class="text-center"><i class="fa fa-times text-danger"></i></td>
@endif
@endforeach
@endfor
<td class="text-success text-center">{{ $count }} / {{ Carbon\Carbon::Now()->daysInMonth }}</td>
</tr>
@endforeach
这不是它应该如何工作的方式,但我已经尝试了很多方法,但仍然找不到合适的方法。 这是我想要实现的图片,以及我的代码
解决方法
这样的事情怎么样:遍历日期并根据日期过滤员工的出勤。
//First,create a date period.
//use Carbon\Carbon; use Carbon\CarbonPeriod;
$daysOfThisMonth = CarbonPeriod::create(Carbon::now()->startOfMonth(),Carbon::now()->endOfMonth());
//Loop through the days
foreach($daysOfThisMonth as $day){
//firstWhere will return one row if day exists in check_in field (equivalent to true),otherwise will return nothing,which will be equivalent to a false.
if( $employee->attendance->firstWhere('check_in',$day ) ) //formatthe dates according to your preference
echo "attended - print tick";
else
echo "not attended - print x";
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。