php - 如何根据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 的命中排序。
解决方案
像这样使用
$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);
推荐阅读
- c - python和c for循环的区别
- java - 输入一个数字,从Java中的给定样本中输出固定数字
- ruby-on-rails - Rails:NoMethodError at /projects/2/model/new undefined method `name' for []:Array
- mysql - 如何在 MySQL Workbench 中导出视图?
- sql-server - 如果 XML 数据中出现特定文本,如何添加新行?
- reactjs - 在数据网格编辑弹出表单时根据在另一个字段上选择的值显示/隐藏字段
- rust - 为什么带有保护子句的匹配模式并不详尽?
- android - React Native:按下后完成当前屏幕(组件)
- php - 使用 Jquery 和 Ajax 创建自动完成/自动建议列表,其中包含使用 PHP 从 API 检索的 JSON 数据
- javascript - 我希望使用 tablesorter 在加载时按特定顺序对表进行排序