laravel 4:如何在更新行时从列的当前值中减去一?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19307202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
laravel 4: how to subtract one from current value of column when updating rows?
提问by Meddie
I was wondering how to perform something like this:
我想知道如何执行这样的事情:
Table::update(array('position'=>'position+1'));
As far as I know, laravel 4 handles 'position+1' as a string, thus is becomes 0.
据我所知,laravel 4 将 'position+1' 作为字符串处理,因此变为 0。
I want to perform something like
我想执行类似的操作
UPDATE table SET position = position + 1
Can I do that using eloquent?
我可以使用 eloquent 做到这一点吗?
EDIT: nevermind, doh.."DB::table('users')->increment('votes');"
编辑:没关系,doh .."DB::table('users')->increment('votes');"
回答by rmobis
Simply make use of the increment
method:
只需使用该increment
方法:
DB::table('users')->increment('position');
The same is valid for decrement
:
这同样适用于decrement
:
DB::table('users')->decrement('rank');
You may even set the second parameter to the amount you want to add/subtract:
您甚至可以将第二个参数设置为要添加/减去的数量:
DB::table('users')->increment('posts', 5);
DB::table('users')->decrement('likes', 3);
Also, if you need to update other columns along with it, you pass it as the third parameter:
此外,如果您需要同时更新其他列,请将其作为第三个参数传递:
DB::table('users')->increment('range', 3, array(
'name' => 'Raphael',
'rank' => 10
));
And the same goes for Eloquent
models, as well:
而且同样适用于Eloquent
模型,以及:
$firstUser = User::find(1);
$firstUser->increment('height', 0.1, array(
'active' => false
));
回答by utsav
you can also do with DB::raw method like this:
你也可以像这样使用 DB::raw 方法:
DB::table('tablename')->where(your condition)->update(['position' => DB::raw('position+1')]);
you can also do other operations with this like
你也可以用这个做其他操作
DB::table('tablename')->where(your condition)->update(['position' => DB::raw('position * 2')]);
回答by Sajjad Ashraf
This worked fine for me
这对我来说很好用
\Models\User::where("id", $userId)->increment("points");
回答by Cyrec
simply you can use the DB::raw method like this:
Table::update(DB::raw('position=position+1'));
简单地你可以像这样使用 DB::raw 方法:
Table::update(DB::raw('position=position+1'));