【问题标题】:Search criteria based on few parameter Laravel基于少量参数 Laravel 的搜索条件
【发布时间】:2019-08-12 05:36:40
【问题描述】:

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

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();
                    }
                }
            }
        }
    }
}

【问题讨论】:

  • 把每个->where分开,放到相关的if条件下。最后打电话给$car->get()

标签: php mysql laravel search eloquent


【解决方案1】:

将条件分成几个 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();

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

【讨论】:

  • Okey 现在标准不起作用属性。我得到了汽车的所有结果。 public function searchFilterCar(Request $request, Car $car) { if ($request->has('car_type')) { $car->where('car_type', $request->input('car_type')); } if ($request->has('mark')) { $car->where('mark', $request->input('mark')); } if ($request->has('model')) { $car->where('model', $request->input('model')); ....... 返回 $car->get(); }
  • 嗯,你能检查一下它是否正在输入 if 语句吗?也可以试试$car = $car->where('car_type', $request->input('car_type'));
  • $car = $car->where('car_type', $request->input('car_type'));这是完美的工作。谢谢你。
  • 随时伴侣。请接受我的回答。我也会编辑它
【解决方案2】:

与 Khaldoun Nd 的答案类似的另一种方法是使用查询条件。它允许您删除后续的 if 语句。

代码会变成这样:

return $car
    ->when($request->car_type, function ($query, $type) {
        return $query->where('car_type', $type);
    })
    ->when($request->mark, function ($query, $mark) {
        return $query->where('mark', $mark);
    })
    // Chain the other conditions like the previous ones...
    ->get();

供参考:https://laravel.com/docs/5.8/queries#conditional-clauses

【讨论】:

    猜你喜欢
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 1970-01-01
    • 2017-09-07
    • 2014-03-04
    相关资源
    最近更新 更多