在 laravel 中使用软删除表和查询有一个小技巧:
当我们创建类似的东西时
$objCars = Car::where("color","blue");
系统执行如下操作:
SELECT
*
FROM
cars
WHERE
deleted_at IS NULL
AND
"color" = 'blue'
到现在为止还挺好。但是,当我们应用“orWhere”方法时,会发生一些有趣的事情
$objCars = Car::where("color","blue")->orWhere("color","red");
系统将执行类似的操作:
SELECT
*
FROM
cars
WHERE
deleted_at IS NULL
AND
"color" = 'blue'
OR
"color" = 'red'
这个新查询将返回deleted_at 为空且颜色为蓝色或颜色为红色的所有汽车,即使deleted_at 不为空。这与其他查询的行为相同,更明确地显示了问题:
SELECT
*
FROM
cars
WHERE
(
deleted_at IS NULL
AND
"color" = 'blue'
)
OR
"color" = 'red'
为了避免这个问题,你应该改变传递闭包的“where”方法。像那样:
$objCars = Car::where(
function ( $query ) {
$query->where("color","blue");
$query->orWhere("color","red");
}
);
然后,系统将执行类似的操作:
SELECT
*
FROM
cars
WHERE
deleted_at IS NULL
AND
(
"color" = 'blue'
OR
"color" = 'red'
)
最后一个查询,搜索所有已删除_at 为空且颜色可以是红色或蓝色的汽车,正如我们希望的那样。