Laravel 减少列值但不是负数
Laravel decrement column value but not negative
我知道我可以使用此查询减少 laravel 中的列值
DB::table('users')->decrement('votes', 5);
但是我想限制这个值不变成负值。
有没有办法用 laravel 做这个?
您需要为此使用原始查询。
以下代码应该适用于所有支持 GREATEST 函数的数据库引擎:
DB::table('users')->update(['votes' => DB::raw('GREATEST(votes - 5, 0)')]);
它将用户table中的投票列减少5,但不会低于零-就是这样GREATEST 函数用于。
如果你真的想在这种情况下使用递减(例如,如果你通过关系访问它会很方便),你可以这样做:
$thing->decrement('votes', $thing->votes - $amount <= 0 ? $thing->votes : $amount);
其中 $amount
在您的例子中是 5。在我看来这很丑陋。值得注意的是,如果您已经拥有 $thing(比如通过关系),则在访问投票时不会触发额外的查询。
如果您只递增 1,简单地 if
环绕会更干净:
if($thing->votes > 0) {
$thing->decrement('votes');
}
我知道我可以使用此查询减少 laravel 中的列值
DB::table('users')->decrement('votes', 5);
但是我想限制这个值不变成负值。
有没有办法用 laravel 做这个?
您需要为此使用原始查询。
以下代码应该适用于所有支持 GREATEST 函数的数据库引擎:
DB::table('users')->update(['votes' => DB::raw('GREATEST(votes - 5, 0)')]);
它将用户table中的投票列减少5,但不会低于零-就是这样GREATEST 函数用于。
如果你真的想在这种情况下使用递减(例如,如果你通过关系访问它会很方便),你可以这样做:
$thing->decrement('votes', $thing->votes - $amount <= 0 ? $thing->votes : $amount);
其中 $amount
在您的例子中是 5。在我看来这很丑陋。值得注意的是,如果您已经拥有 $thing(比如通过关系),则在访问投票时不会触发额外的查询。
如果您只递增 1,简单地 if
环绕会更干净:
if($thing->votes > 0) {
$thing->decrement('votes');
}