首页 > 解决方案 > 查询是否为空值

问题描述

当我有多个可以为空的变量时,是否有更好的方法来构造一个 mysql 查询来处理“为空”?

DB::connection('mysql')->select('select * from db where width = ? and height = ? and length = ? and color = ?', [$width, $height, $length, $color]);

代替

if ($width == null) {
  DB::connection('mysql')->select('select * from db where width is null and height = ? and length = ? and color = ?',[$height, $length, $color]);
}elseif($height == null) {
...

标签: phpmysqllaravel

解决方案


此答案可能不会使用您的表格。但我很久以前偶然发现了这一点。在我的示例中,我使用模型、列名和列值的数组。

数组:

$filterData = [
  'width' => 21.0,
  'height' => 11.5,
  'length' => null
];

查询:

$mainQuery = Furniture::where($filterData);

要查看输出:$mainQuery->toSql();


推荐阅读