簡體   English   中英

如何在 laravel 中的 foreach 循環后部署分頁

[英]How can i deploy pagination after foreach loop in laravel

我正在嘗試在搜索結果中創建分頁。 我的存儲庫中有一個查詢,例如:

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 循環。

請幫忙。

您可以像以前一樣對初始查詢進行分頁,然后像常規集合一樣遍歷分頁 object 或使用$pagination->items()

您還應該在初始查詢中使用嵌套with('relation')來停止 N+1 個查詢https://laravel.com/docs/8.x/eloquent-relationships#constraining-eager-loads

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM