Php 当某些值可能为空时,如何通过多个输入筛选电子商务商店中的产品

Php 当某些值可能为空时,如何通过多个输入筛选电子商务商店中的产品,php,laravel,Php,Laravel,我有几个输入,以便在网上商店过滤产品。我的问题是,如果一些输入没有填充/选择,我如何过滤产品。我该如何查询 public function find() { $categories = Category::all(); if (isset($_GET['submit'])) { if (!empty($_GET['brand'])) { $selectedBrand = $_GET['brand']; echo

我有几个输入,以便在网上商店过滤产品。我的问题是,如果一些输入没有填充/选择,我如何过滤产品。我该如何查询

public function find()
{
    $categories = Category::all();

    if (isset($_GET['submit'])) {

        if (!empty($_GET['brand'])) {
            $selectedBrand = $_GET['brand'];
            echo 'You have chosen: ' . $selectedBrand;
        } else {
            echo 'Please select the value.';
        }
        $date = Request::get('date');
        $name = Request::get('name');

        $selected = $_GET['type'];
        $data = DB::table('product')->where('product.type', $_GET['type'])
            ->where('product.name', $name)
            ->join('shop', 'product.id', '=', 'shop.product_id')
            ->where('shop.releasedate', $date)
            ->get();
        return view('pages/catalog')->with(['product' => $data, 'categories' => $categories]);
    }
}

您可以先检查字段是否已填充,然后继续使用查询模型

逻辑

$date=null;
如果($request->filled('date)){
$date=$request->date;
}
//您的其他值可以像上面一样放在这里
$data=DB::table('product')->其中('product.type',$\u GET['type'])
->其中('product.name',$name)
->加入('shop','product.id','=','shop.product_id'))
->when($date,function($query,$transmission){
//仅当$date为“true”(有值且不为空)时,此查询才会运行
return$query->where('shop.releasedate','=',$date);
->orderBy('shop.created_at','desc');
},函数($query){
//如果$date为'false'(空),则要返回的内容
})
->get();

很长一段时间以来,许多人习惯用“if-else”编写条件查询。 如果我告诉你有更好的方法呢?易读且更为宽泛。满足
when()
方法

$brandId = $request->brand;
$date = $request->date;

$filteredProducts = Product::when($brand, function ($product, $brand) {
    return $product->where('brand_id', $brandId);
})->when($date, function ($product, $date) {
    return $product->where('created_at', $date);
})->get();
您可以对用户发送的所有参数执行相同的操作

看起来比“如果/否则”更好,不是吗

when
方法仅在第一个参数为
true
时执行给定的闭包。如果第一个参数为
false
,则不会执行闭包。因此,在上面的示例中,只有当传入请求中存在
$brandId
$date
字段并且计算结果为true时,才会调用
when
方法的闭包