
本文旨在解决 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;
}代码解释:
这是一个在线展示企业网站范例的源代码,涉及36个行业分类近500个精美企业网站程序范例——不论是对美工还是程序员,都有相当高的参考价值! 使用 后台管理:登录用户为“admin”,登录密码为“admin888”,登录页面为“Manage.asp”。 包含“管理员管理/添加网站/管理网站/数据库和上传文件管理”的完整功能。 其他 请把数据库后缀名MDB改为ASP防下载,同时修改两个Conn.asp
- 获取分页参数: 首先从 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 项目中实现该功能。









