Laravel减少列值而不是负值

问题描述 投票:4回答:2

我知道我可以使用此查询减少laravel中的列值

DB::table('users')->decrement('votes', 5);

但我想限制价值成为负值。

无论如何用laravel做到这一点?

php laravel laravel-5 eloquent laravel-5.2
2个回答
4
投票

您需要使用原始查询。

以下代码应该为所有支持GREATEST功能的数据库引擎提供技巧:

DB::table('users')->update(['votes' => DB::raw('GREATEST(votes - 5, 0)')]);

它会将用户表中的投票列减少5,但不会低于零 - 这就是GREATEST函数的用途。


1
投票

如果你真的想在这种情况下使用减量(例如,如果你通过关系访问它可以很方便),你可以做类似的事情:

$thing->decrement('votes', $thing->votes - $amount <= 0 ? $thing->votes : $amount);

在你的情况下$amount是5。在我看来这很丑陋。值得注意的是,如果你已经拥有$ thing(比如通过关系),它在访问投票时不会触发额外的查询。

如果你只增加1,简单的if缠绕更清洁:

        if($thing->votes > 0) {
            $thing->decrement('votes');
        }
© www.soinside.com 2019 - 2024. All rights reserved.