当我有多个变量可以为空时,有没有更好的方法来构造一个mysql查询来处理"is null"?
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) {
...发布于 2021-02-19 13:05:02
此答案可能不使用您的表。但我很久以前就偶然发现了这一点。在我示例中,我使用了model,这是一个由列名和列值组成的数组。
数组:
$filterData = [
'width' => 21.0,
'height' => 11.5,
'length' => null
];查询:
$mainQuery = Furniture::query();
foreach($filterData as $columnName => $columnValue){
$mainQuery = $mainQuery->where($columnName, $columnValue);
}要查看输出,请执行以下操作:$mainQuery->toSql();
发布于 2021-02-19 12:39:57
使用查询构建器解决了我的问题。当变量为null时,它会自动将查询更改为"is null“。
DB::connection('mysql')->table('db')->where('width', $width)->where('height', $height)->where('length', $length)->where('color', $color)->get();https://stackoverflow.com/questions/66271382
复制相似问题