我正在编写一个搜索函数,它使用三个参数:品牌、型号和燃料类型。“make”参数是必需的,因此我首先使用下面的代码将 make 及其相关模型选择到集合中。
// Find Make and Models
$makeAndModels = Make::where('name', $request->make)->with('carmodels', 'carmodels.fueltype')->first();
此时集合看起来像这样:
{
"id": 2,
"name": "Toyota",
"created_at": "2020-07-26T16:11:06.000000Z",
"updated_at": "2020-07-26T16:11:06.000000Z",
"carmodels": [
{
"id": 3,
"name": "Prius",
"make_id": 2,
"fueltype_id": 2,
"created_at": "2020-07-26T16:44:21.000000Z",
"updated_at": "2020-07-26T16:44:21.000000Z",
"fueltype": {
"id": 2,
"name": "Hybrid",
"created_at": "2020-07-26T16:11:06.000000Z",
"updated_at": "2020-07-26T16:11:06.000000Z"
}
},
{
"id": 4,
"name": "Hilux",
"make_id": 2,
"fueltype_id": 3,
"created_at": "2020-07-26T16:44:21.000000Z",
"updated_at": "2020-07-26T16:44:21.000000Z",
"fueltype": {
"id": 3,
"name": "Diesel",
"created_at": "2020-07-26T16:11:06.000000Z",
"updated_at": "2020-07-26T16:11:06.000000Z"
}
}
]
}
然后,我想按名称和燃料类型过滤“汽车模型”子集合,将过滤后的数据返回到其原始集合,而不是返回到新集合。这些过滤器仅应在提供了附加参数的情况下运行,我当前使用的代码如下所示。
//Filter Models By Additional Parameters
//Model
if ($request->model) {
$model = $request->model;
$makeAndModels->carmodels = $makeAndModels->carmodels->filter()->where('name', $model);
}
由于某种原因,这种过滤方式不会覆盖原始集合,例如,如果我过滤到新的子集合,
//Filter Models By Additional Paramters
//Model
if ($request->model) {
$model = $request->model;
$makeAndModels->carmodelsFiltered = $makeAndModels->carmodels->filter()->where('name', $model);
}
它产生以下结果,所以我知道过滤器应该起作用。
POPMUISE