Laravel 中使用 whereIn 和请求参数进行排序分页

laravel 中使用 wherein 和请求参数进行排序分页

本文旨在解决 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() 方法可以链式调用,以便添加多个排序条件。可以根据实际需求,使用不同的排序字段和排序方式(asc 或 desc)。Session 的使用应谨慎,可以考虑使用更可靠的方式传递分页参数,例如 query string。

总结:

通过在执行 paginate() 方法之前,将排序条件添加到查询构建器中,可以避免在集合上进行排序操作,从而解决 “orderBy doesn’t exist on collection” 的错误。这种方法可以灵活地根据用户的请求参数对数据库查询结果进行排序和分页,提高应用程序的性能和用户体验。

以上就是Laravel 中使用 whereIn 和请求参数进行排序分页的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1321172.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月12日 07:28:30
下一篇 2025年12月12日 07:28:39

相关推荐

发表回复

登录后才能评论
关注微信