
本文旨在解决 Laravel 中使用 whereIn 查询数据后,根据用户请求参数动态排序并进行分页的问题。核心在于将排序操作应用于查询构建器(query builder)对象,而非分页后的集合(collection)对象,从而避免 orderBy 方法不存在的错误。通过本文提供的示例代码,你可以灵活地根据用户需求对数据进行排序和分页,提升用户体验。
在 Laravel 中,如果需要在 whereIn 查询后根据用户请求动态排序并进行分页,需要注意 orderBy() 方法的使用位置。直接对 paginate() 方法返回的集合(Collection)对象调用 orderBy() 会导致 "orderBy doesn't exist on collection" 的错误,因为集合对象没有 orderBy 方法。正确的做法是在执行 paginate() 之前,将 orderBy() 应用于查询构建器(Query Builder)对象。
以下是一个详细的示例:
use App\Models\Product;
use App\Models\ProductCategories;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
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;
}代码解释:
注意事项:
总结:
在 Laravel 中,当需要使用 whereIn 查询数据后根据请求参数动态排序并进行分页时,务必将 orderBy() 方法应用于查询构建器对象,而不是分页后的集合对象。 这样可以避免 "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号