同时遍历多个集合

时间:2019-03-30 09:28:42

标签: laravel

我已经看过几次这个问题,但在每种情况下都不清楚解决方案是什么。

我需要遍历2个集合,一个集合包含员工信息,另一个集合包含这些员工的预订

如果嵌套的for循环意味着操作将首先循环遍历内部循环直到完成,并且每次外部循环递增时重复一次,我都不愿意使用嵌套的for循环

@foreach($Employees as $Employee, $bookings as $booking)
        // return somethuing
@endforeach

2 个答案:

答案 0 :(得分:1)

您可以查询Booking,以使结果被employee_id索引

假设每个bookings有多个employee

$employees = Employee::get();
$bookings = Booking::get();
$bookings = collect($bookings)->groupBy('employee_id');

@foreach($employees as $employee)
    @if(isset($bookings[$employee->id]))
        @foreach($bookings[$employee->id] as $booking)
            //you can get all the bookings of each employee

        @endforeach
    @endif
@endforeach

如果每个employee都有一个booking

$employees = Employee::get();
$bookings = Booking::get()->keyBy('employee_id');

@foreach($employees as $employee)
    @if(isset($bookings[$employee->id]))
        //you can get the booking of each employee

    @endif
@endforeach

答案 1 :(得分:0)

请尝试在员工和预订之间建立关系,就像员工有很多预订一样。阅读官方(docs)中的 Laravel关系

然后在您的控制器中,可以通过其预订获取员工。像这样:

$Employees = Employee::with('bookings')->get();
// here is try to make your own query.

return view('your_view', compact('Employees'));

然后在您的刀片式服务器中:

@foreach($Employees as $Employee)
    @foreach($Employee->bookings as $booking)
        {{ $booking }}
    @endforeach
@endforeach

我希望这会有所帮助。