php - 当某些值可以为空时如何通过许多输入过滤电子商务商店中的产品
问题描述
我有几个输入来过滤在线商店中的产品。我的问题是,如果某些输入没有被填充/选择,我该如何过滤产品。我应该如何查询?
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]);
}
}
解决方案
您可以先检查您的字段是否已填写,然后使用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();
推荐阅读
- javascript - 如何根据对象值返回布尔值?
- python - 输出音频不过是静态的
- macos - lsof 是否有替代选项来检测 macOS 上进程的打开文件?
- windows - 在 Windows 上使用 Poco(启用 Crypto/NetSSL)编译项目并在 Linux ARM 上交叉编译
- python-3.x - 我想知道如何缩短此代码并使其看起来更合适
- java - 为什么`Outer.Inner inner = o.new Inner();`而不是`Outer.Inner inner = o.new Outer.Inner();`?
- python - 有没有办法在安装时重命名python包?
- powershell - 如何在 Powershell 中修剪管道对象并在管道中进一步使用它?
- java - 找出总距离
- discord.js - 向一组用户发送私人消息(Discord.js)