首页 > 解决方案 > 如何根据laravel中的2个不同条件对查询进行排序

问题描述

我在 laravel 中有一个查询,我希望我的用户能够以 2 种不同的方式对其进行排序。其中一个是 hits,它是它自己字段的模型,但另一个是与该模型相关的字段:

  $data = Accommodation::with(['city','accommodationFacilities','gallery', 'accommodationRoomsLimited.roomPricingHistorySearch' => function ($query) use ($from_date, $to_date) {
        $query->whereDate('from_date', '<=', $from_date);
        $query->whereDate('to_date', '>=', $to_date);
    }])->when($bed_count, function ($q, $bed_count) {
        $q->with([
            'accommodationRoomsLimited' => function ($q) use ($bed_count) {
                $q->where('bed_count', $bed_count);
            }
        ]);
    })
        ->whereIn('city_id', $city_id)
        ->whereIn('grade_stars', $stars)
        ->orWhere('accommodation_type_id', $type_id)
        ->paginate(10);

所以在上面提交的点击数存在于住宿模型中价格在 roomPricingHistorySearch 我希望我的 api 按用户发送给它的 2 个中的任何一个排序我认为如果用户发送 sort_price 例如它按价格排序并且如果用户发送 sort_hit 它按 api 的命中排序。

标签: phplaravel

解决方案


像这样使用


 $data = Accommodation::with(['city','accommodationFacilities','gallery', 'accommodationRoomsLimited.roomPricingHistorySearch' => function ($query) use ($from_date, $to_date) {
        $query->whereDate('from_date', '<=', $from_date);
        $query->whereDate('to_date', '>=', $to_date);
    }])->when($bed_count, function ($q, $bed_count) {
        $q->with([
            'accommodationRoomsLimited' => function ($q) use ($bed_count) {
                $q->where('bed_count', $bed_count);
            }
        ]);
    })
        ->whereIn('city_id', $city_id)
        ->whereIn('grade_stars', $stars)
        ->orWhere('accommodation_type_id', $type_id);

if(request()->sort_hit ){ // or == 'blabla'
    $data = $data->orderBy('hit');
}elseif(request()->sort_price){ // == A-Z or Z-A for order asc,desc
    $data = $data->orderBy('price');
}

$data = $data->paginate(10);



推荐阅读