繁体   English   中英

通过请求在 laravel 中的位置排序

[英]order by where in in laravel with requests

我想根据每个用户的要求订购产品,代码如下,这是代码

$pagination = \Session::get('page');
if(\Session::get('page') == NULL){
    \Session::put('page',12);
}
if($request->has('per_page')){
    \Session::put('page',$request->per_page);
    $pagination = Session::get('page');
}
$pris = product_categories::where('category_id', $id)->pluck('product_id')->toArray();
$products = Product::whereIn('id' , $pris)->paginate($pagination);
$pagination = \Session::get('page');
if($request->get('sort') == 'price_asc'){
    $products = $products->OrderBy('price','asc');
}elseif($request->get('sort') == 'price_desc'){
    $products = $products->OrderBy('price','desc');
}elseif($request->get('sort') == 'popular'){
    $products =   $products->OrderBy('views','desc');
}elseif($request->get('sort') == 'newest'){
    $products = $products->OrderBy('created_at','desc');
}

它返回错误 orderby 在集合中不存在

在运行 paginate 之前,必须将orderBy()语句添加到查询中:

$productsQuery = Product::whereIn('id' , $pris);
//$pagination = \Session::get('page'); // not sure why this line is there?
if($request->get('sort') == 'price_asc'){
    $productsQuery ->OrderBy('price','asc');
}elseif($request->get('sort') == 'price_desc'){
    $productsQuery ->OrderBy('price','desc');
}elseif($request->get('sort') == 'popular'){
    $productsQuery ->OrderBy('views','desc');
}elseif($request->get('sort') == 'newest'){
    $productsQuery ->OrderBy('created_at','desc');
}
$products = $productsQuery->paginate($pagination);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM