【发布时间】:2025-12-01 11:35:02
【问题描述】:
我做网店。我有 3 个页面,其中产品的过滤器相似 - 目录页面、父类别页面和子类别页面
site/catalog/ // catalogController@index
site/catalog/parentCategory/childrenCategory //childrenCategoryController@index
site/catalog/parentCategory //parentCategoryController@index
过滤器是通过获取请求进行的,例如:site/catalog?price_from=1&price_to=9999&color=red。如何使这个过滤器成为一个单独的函数?在产品模型中制作这个会好吗?以及如何使用它?我认为它应该是一个接受 2 个参数(请求参数和当前查询模型)并返回 $this 的函数。
控制器中的代码:
$products = Product::filter($products, $request)->paginate(20);
型号:
public function filter($model, Request $request) {
if ($request->has('price_from')) {
$model->where('price', '>', $request->get('price_from'));
}
if ($request->has('color')) {
$model->where('color', '>', $request->get('color'));
}
return $model;
}
但是如何正确地做呢?如何在控制器代码中传递当前$products?
【问题讨论】: