
本文旨在解决 Laravel 中在使用 whereIn 方法查询数据后,如何根据用户请求对结果进行排序并进行分页的问题。核心在于将排序操作应用于查询构建器,而非分页后的集合,从而避免 "orderBy doesn't exist on collection" 错误。通过本文,你将学会如何正确地构建查询,并根据用户请求动态地应用排序规则。
在 Laravel 中,经常需要使用 whereIn 方法根据一组 ID 查询数据,并且根据用户的请求对查询结果进行排序。一个常见的错误是在分页之后再尝试使用 orderBy 方法,这会导致 "orderBy doesn't exist on collection" 错误,因为 paginate() 方法返回的是一个 LengthAwarePaginator 实例,而不是查询构建器。
正确的做法是在执行 paginate() 方法之前,将所有的排序条件应用到查询构建器上。
下面是一个示例,展示了如何根据用户请求对 Product 模型进行排序,该模型通过 whereIn 方法基于 product_categories 表中的 category_id 进行筛选:
use App\Models\Product;
use App\Models\ProductCategories;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
public function getProductsByCategory(Request $request, $id)
{
$pagination = Session::get('page', 12); // 默认每页显示12条数据
if ($request->has('per_page')) {
Session::put('page', $request->per_page);
$pagination = $request->per_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 中获取分页大小,如果请求中包含 per_page 参数,则更新 Session 并使用请求中的值。
获取 product_id 列表: 使用 ProductCategories 模型和 where 方法,根据 $id 获取 product_id 列表,并将其转换为数组。
构建基础查询: 使用 Product 模型和 whereIn 方法,根据 product_id 列表构建基础查询。注意,此时还没有执行查询。
应用排序条件: 根据请求中的 sort 参数,动态地应用不同的排序规则。重要的是,这些 orderBy 方法都作用于 $productsQuery 查询构建器,而不是分页后的集合。
执行分页查询: 最后,调用 $productsQuery 的 paginate() 方法执行分页查询。
注意事项:
总结:
在 Laravel 中,当需要对 whereIn 查询的结果进行排序时,关键在于在执行 paginate() 方法之前,将所有的排序条件应用到查询构建器上。 这样可以避免 "orderBy doesn't exist on collection" 错误,并确保正确地对查询结果进行排序和分页。通过上述示例,你应该能够更好地理解如何在 Laravel 中处理复杂的查询需求,并根据用户请求动态地应用排序规则。
以上就是Laravel 中使用 whereIn 查询结果进行排序并处理请求的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号