有没有办法将 2 个 foreach 和一个 for 循环一起循环?

问题描述

我正在从事 Laravel 8 项目,我将在其中创建人力资源管理系统,所以我现在正在努力报告员工出勤情况。 我有2个模型 User.PHPAttendance.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

这不是它应该如何工作的方式,但我已经尝试了很多方法,但仍然找不到合适的方法。 这是我想要实现的图片,以及我的代码

Picture of the final result

My result

解决方法

这样的事情怎么样:遍历日期并根据日期过滤员工的出勤。

//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";
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...