gpt4 book ai didi

php - 基于少量参数的搜索条件 Laravel

转载 作者:行者123 更新时间:2023-11-29 07:22:59 25 4
gpt4 key购买 nike

只有当我正确填写所有字段时,此搜索才对我有用。我的愿望是,当我只填写一个字段时,我将排除仅与该字段相关的结果。例如,如果我只用“Audi”填写“mark”字段,就会得到我的商标名称。我的函数当前仅在所有字段都已填写时才返回结果。如果我填写一个字段,它会返回一个空数组。另外,我不确定这个功能是否写得很好,我按照教程进行了操作。看代码:

public function searchFilterCar(Request $request, Car $car){
if($request->has('car_type')){
if($request->has('mark')){
if($request->has('model')){
if($request->has('fuel')){
if($request->has('circuit')){
return $car->where('car_type', $request->input('car_type'))
->where('mark', $request->input('mark'))
->where('model', $request->input('model'))
->where('fuel', $request->input('fuel'))
->where('circuit', $request->input('circuit'))
->get();
}
}
}
}
}
}

最佳答案

将条件分成多个 if 语句,where 对现有结果起作用,因此您将从之前的 where 继续。它应该是这样的:

    if($request->has('car_type')){
$car = $car->where('car_type', $request->input('car_type'));
}

if($request->has('mark')){
$car = $car->where('mark', $request->input('mark'));
}

....

return $car->get();

它可能看起来有点粗糙,但它减小了代码块的大小并且它有效

关于php - 基于少量参数的搜索条件 Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55279175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com