我正在尝试根据价格(从最低到最高,从最高到最低)对数据库记录(游览)进行排序。我在db中添加了12条虚拟记录,其中价格分别为100到1200。下面是我在控制器中执行排序查询的代码:
public function short(Request $request)
{
if ($request->sortby == "lower") {
$query = Tour::query()->orderBy('price', 'asc');
if (!empty($request->country)) {
$query = $query->whereHas('country', function($r) use($request) {
$r->where('countries.name', $request->country);
});
}
if (!empty($request->category)) {
$query = $query->whereHas('category', function($s) use($request) {
$s->where('categories.name', $request->category);
});
}
if ($request->days !== null) {
$days = $request->days;
$days_explode = explode('|', $days);
$query = $query->whereBetween('days', [$days_explode[0], $days_explode[1]]);
}
$query = $query->get();
}
else{
$query = Tour::query()->orderBy('price', 'desc');
if (!empty($request->country)) {
$query = $query->whereHas('country', function($r) use($request) {
$r->where('countries.name', $request->country);
});
}
if (!empty($request->category)) {
$query = $query->whereHas('category', function($s) use($request) {
$s->where('categories.name', $request->category);
});
}
if ($request->days !== null) {
$days = $request->days;
$days_explode = explode('|', $days);
$query = $query->whereBetween('days', [$days_explode[0], $days_explode[1]]);
}
$query = $query->get();
}
return view('public.tour.search')->withResults($query);
}
如果选择从最低到最高排序,则根据db表的价格价格列按以下顺序显示记录:
100,1000,1100,1200,200,300,400,500,600,700,800,900
当选择从最高到最低时,根据db table的价格价格列按以下顺序显示记录:
900,800,700,600,500,400,300,200,1200,1100,1000,100
有人可以帮我吗?
答案 0 :(得分:1)
将Order By Query放在最后。
$query = $query->orderBy('price', 'asc')->get();
答案 1 :(得分:-1)
数据库中price
列的数据类型是什么?
它应该是double
或integer
之类的数字格式,以便排序正常工作。