
本文旨在解决 Laravel 中在使用 whereIn 查询后,根据用户请求参数对结果进行排序和分页的问题。核心思路是在执行 paginate() 方法之前,将所有的排序条件添加到查询构建器中,避免在集合上进行排序操作,从而解决 "orderBy doesn't exist on collection" 的错误。
在 Laravel 中,经常需要根据用户的请求参数对数据库查询结果进行排序和分页。当使用 whereIn 方法进行条件查询时,如果直接在 paginate() 方法返回的集合上使用 orderBy() 方法,会遇到 "orderBy doesn't exist on collection" 的错误。这是因为 paginate() 方法返回的是一个 LengthAwarePaginator 实例,而不是一个查询构建器,所以不能直接使用 orderBy() 方法。
以下是如何正确实现排序和分页的步骤:
构建查询:首先,使用 whereIn 方法构建查询,并将查询构建器存储在一个变量中。
$pris = product_categories::where('category_id', $id)->pluck('product_id')->toArray();
$productsQuery = Product::whereIn('id' , $pris);添加排序条件:根据用户的请求参数,使用 orderBy() 方法向查询构建器添加排序条件。
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');
}执行分页:最后,在查询构建器上调用 paginate() 方法,执行分页操作。
$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');
}
$products = $productsQuery->paginate($pagination);完整代码示例:
$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();
$productsQuery = Product::whereIn('id' , $pris);
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);注意事项:
总结:
通过在执行 paginate() 方法之前,将排序条件添加到查询构建器中,可以避免在集合上进行排序操作,从而解决 "orderBy doesn't exist on collection" 的错误。这种方法可以灵活地根据用户的请求参数对数据库查询结果进行排序和分页,提高应用程序的性能和用户体验。
以上就是Laravel 中使用 whereIn 和请求参数进行排序分页的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号