上下文:我正在尝试计算员工在约会中工作的总小时数,并在刀片视图中按员工显示总小时数。我可以成功地总结每个 $EmployeeHours 的 $starts_at 减去 $ends_at 日期的小时数。但是当我 dd(); 时我只看到最后一个对象,而不是集合。
当我尝试发送数据以在 @foreach 循环中查看时,出现错误:
array_merge():参数 #2 不是数组
当我保存到数据库中的表时,它成功地迭代并保存我期望的每个 $EmployeeHours。
问题是我不想将查询结果保存到数据库,我只想显示到刀片,因为它只是要提取的用户报告的查询。
$EmployeeHours = DB::table('appointment_employee')
->join('appointments', 'appointment_id', '=', 'appointments.id')
->join('employees', 'employees.id', '=', 'appointment_employee.employee_id')
->join('users', 'users.id', '=', 'employees.user_id')
->where('role_id', '=', '1')
->get()->groupby('id');
$results=[];
foreach($EmployeeHours as $EmployeeHour)
{
$duration = [];
foreach($EmployeeHour as $collection)
{
$date1 = $collection->starts_at;
$date2 = $collection->ends_at;
$start = Carbon::parse($date1);
$end = Carbon::parse($date2);
$length = $start->diffInMinutes($end)/60;
$duration[] = $length;
}
$totalHours = array_sum($duration);
//I think here is where I am going wrong possibly
$results = [
'totalHours' => $totalHours,
'employee_name' => $collection->first_name. " ".$collection->last_name,
];
}
dd($EmployeeHour);
return view ('admin.invoices.reporting.employeeHours',$results);
这是刀片视图
@foreach($results as $result)
<tr>
<td>{{ $result->employee_name }}</td>
<td>{{ $result->totalHours }}</td>
</tr>
@endforeach
我也尝试过在 Blade 中不使用 foreach 循环,它返回最后一个对象 i,e 。
<tbody>
<tr>
<td>{{ $employee_name }}</td>
<td>{{ $totalHours }}</td>
</tr>
</tbody>
有两件事对我来说很突出......
$results
而不是附加到它。尝试:
$results = [];
foreach ($EmployeeHours as $EmployeeHour) {
$duration = [];
$name = null;
foreach ($EmployeeHour as $collection) {
$date1 = $collection->starts_at;
$date2 = $collection->ends_at;
$start = Carbon::parse($date1);
$end = Carbon::parse($date2);
$length = $start->diffInMinutes($end)/60;
$duration[] = $length;
if (is_null($name)) {
$name = $collection->first_name . " " . $collection->last_name;
}
}
$totalHours = array_sum($duration);
// Notice I added [], this will append it to the array instead of replacing it.
$results[] = [
'totalHours' => $totalHours,
'employee_name' => $name,
];
}
// Notice I used `compact()` which is the same as doing ['results' => $results]
return view('admin.invoices.reporting.employeeHours', compact('results'));
我同意 Jono20201 的观点,你应该重构以利用 Eloquent ORM。
您每次都将
$results
设置为新数组,而实际上您想在每次交互时添加到 $results
数组。
$results[] = [
'totalHours' => $totalHours,
'employee_name' => $collection->first_name . " " . $collection->last_name,
];
ps。您确实应该尝试将其重构为使用 Eloquent 模型/关系,而不是使用查询生成器。
你应该改变这个:
$results = [
'totalHours' => $totalHours,
'employee_name' => $collection->first_name. " " . $collection->last_name,
];
对此:
$results[] = [
'totalHours' => $totalHours,
'employee_name' => $collection->first_name. " ".$collection->last_name,
];
当您不使用括号时,您会将数组值替换为新值,使用括号在每次迭代中将新值附加到数组中。