我如何在 Laravel 中的 foreach 循环之后部署分页

问题描述

我正在尝试在我的搜索结果中创建一个分页。我的存储库中有一个查询,例如:

public function getFilteredVehicles($id,$pax,$categories,$search_type,$from_date,$to_date)
{
    $vehicles = Vehicle::whereHas('destinations',function($q) use($id){
        $q->where('destination_id',$id)
            ->where('active',1);
        })
        ->paginate(1);

    if($search_type == 'disposal' || $search_type == 'pnd')
    {
        $vehicles = $vehicles->where('registered_location',$id);
    }

    if($categories)
    {
        $vehicles = $vehicles->where('vehicle_categoryid',$categories);
    }

    return $vehicles;
}

返回的结果再次需要通过如下循环处理:

public function calculateLocationAmount($vehicles,$fdate,$tdate,$destination_id)
{
    $datetime1 = new DateTime($fdate);
    $datetime2 = new DateTime($tdate);

    $interval = $datetime1->diff($datetime2);
    $days = $interval->format('%a');
    $days = $days+1;
    $nights = $days-1;

    foreach ($vehicles as $key => $vehicle) {
        # code...
        $perday_rate = $vehicle->destinations->where('id',$destination_id)->first()->pivot->day_rate;
        $pernight_rate = $vehicle->destinations->where('id',$destination_id)->first()->pivot->night_rate;

        $day_rate = $perday_rate * $days;
        $night_rate = $pernight_rate * $nights;
        $total_amount = $day_rate + $night_rate;
        $vehicle['total_amount'] = $total_amount;
        $vehicle['availability'] = 'true';

        if($vehicle->whereHas('unavailability',function($q) use($fdate,$tdate){
                            $q->whereRaw("? BETWEEN `from_date` AND `to_date`",[$fdate])
                                ->orwhereRaw("? BETWEEN `from_date` AND `to_date`",[$tdate]);
                        })->count()>0){
            $vehicle['availability'] = 'false';
        }
    }
    
    return $vehicles;
}

这个最终结果需要分页。我该怎么做?

由于链接不起作用,使用 foreach 将值更改为集合。如果我不执行 paginate()get(),则不会执行 for 循环。

请帮忙。

解决方法

您可以按原样对初始查询进行分页,然后循环分页对象,就好像它是您的常规集合一样,或者使用 $pagination->items()

您还应该在初始查询中使用嵌套的 with('relation') 来停止 N+1 查询 https://laravel.com/docs/8.x/eloquent-relationships#constraining-eager-loads