
本文旨在解决 Laravel 中使用 whereIn 查询数据后,根据用户请求参数动态排序并进行分页的问题。核心在于将排序操作应用于查询构建器(query builder)对象,而非分页后的集合(collection)对象,从而避免 orderBy 方法不存在的错误。通过本文提供的示例代码,你可以灵活地根据用户需求对数据进行排序和分页,提升用户体验。
在 Laravel 中,如果需要在 whereIn 查询后根据用户请求动态排序并进行分页,需要注意 orderBy() 方法的使用位置。直接对 paginate() 方法返回的集合(Collection)对象调用 orderBy() 会导致 “orderBy doesn’t exist on collection” 的错误,因为集合对象没有 orderBy 方法。正确的做法是在执行 paginate() 之前,将 orderBy() 应用于查询构建器(Query Builder)对象。
以下是一个详细的示例:
use AppModelsProduct;use AppModelsProductCategories;use IlluminateHttpRequest;use IlluminateSupportFacadesSession;public function getProducts(Request $request, $id){ $pagination = Session::get('page'); if (Session::get('page') == null) { Session::put('page', 12); $pagination = 12; } if ($request->has('per_page')) { Session::put('page', $request->per_page); $pagination = Session::get('page'); } $productIds = ProductCategories::where('category_id', $id)->pluck('product_id')->toArray(); // 创建查询构建器对象 $productsQuery = Product::whereIn('id', $productIds); // 根据请求参数动态排序 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); return $products;}
代码解释:
获取分页参数: 首先从 Session 中获取分页大小,如果 Session 中没有设置,则默认设置为 12。如果请求中包含 per_page 参数,则更新 Session 中的分页大小。获取产品 ID: 使用 ProductCategories 模型查询属于指定分类 ID 的产品 ID,并将其转换为数组。创建查询构建器: 使用 Product::whereIn(‘id’, $productIds) 创建一个查询构建器对象。 注意: 此时并没有真正执行查询。动态排序: 根据请求中的 sort 参数,使用 orderBy() 方法对查询构建器对象进行排序。 关键: orderBy() 方法作用于查询构建器,而非最终结果。执行分页: 调用 paginate() 方法执行分页查询。Laravel 会自动处理分页逻辑,并返回一个 LengthAwarePaginator 实例,其中包含分页数据和分页信息。返回结果: 将分页结果返回。
注意事项:
确保 Product 模型中存在 price, views, created_at 等字段,并且这些字段是数据库中的实际字段。Session::get(‘page’) 和 $request->per_page 应该进行适当的验证和过滤,以防止恶意输入。可以根据实际需求扩展排序条件,例如添加更多的排序字段或排序方式。在大型数据集中,考虑为排序字段添加索引以提高查询性能。使用 ->toSql() 方法可以查看最终生成的 SQL 查询语句,方便调试和优化。例如:dd($productsQuery->toSql());
总结:
在 Laravel 中,当需要使用 whereIn 查询数据后根据请求参数动态排序并进行分页时,务必将 orderBy() 方法应用于查询构建器对象,而不是分页后的集合对象。 这样可以避免 “orderBy doesn’t exist on collection” 的错误,并实现灵活的数据排序和分页功能。通过以上示例和注意事项,你可以轻松地在 Laravel 项目中实现该功能。
以上就是Laravel 中使用 whereIn 和请求参数进行排序及分页的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1321086.html
微信扫一扫
支付宝扫一扫