首页 > 解决方案 > 当某些值可以为空时如何通过许多输入过滤电子商务商店中的产品

问题描述

在此处输入图像描述

我有几个输入来过滤在线商店中的产品。我的问题是,如果某些输入没有被填充/选择,我该如何过滤产品。我应该如何查询?

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

标签: phplaravel

解决方案


您可以先检查您的字段是否已填写,然后使用when 方法继续查询您的模型

逻辑

$date = null;
if($request->filled('date)){
  $date = $request->date;
}
// your other values can go here like above

$data = DB::table('product')->where('product.type', $_GET['type'])
            ->where('product.name', $name)
            ->join('shop', 'product.id', '=', 'shop.product_id')            
            ->when($date, function ($query, $transmission) {
                 // this query runs only if $date is `true` (has a value and not empty)
                 
                 return return $query->where('shop.releasedate','=', $date);
                                     ->orderBy('shop.created_at','desc);                            
            }, function ($query) {
                  // something you want to return if the $date is `false` (empty)
            })
            ->get();


推荐阅读