laravel 4: how to subtract one from current value of column when updating rows?

元气小坏坏 提交于 2019-12-03 16:52:03

问题


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.

I want to perform something like

UPDATE table SET position = position + 1

Can I do that using eloquent?

EDIT: nevermind, doh.."DB::table('users')->increment('votes');"


回答1:


Simply make use of the increment method:

DB::table('users')->increment('position');

The same is valid for 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:

$firstUser = User::find(1);
$firstUser->increment('height', 0.1, array(
    'active' => false
));



回答2:


you can also do with DB::raw method like this:

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')]);



回答3:


This worked fine for me

\Models\User::where("id", $userId)->increment("points");



回答4:


simply you can use the DB::raw method like this: Table::update(DB::raw('position=position+1'));



来源:https://stackoverflow.com/questions/19307202/laravel-4-how-to-subtract-one-from-current-value-of-column-when-updating-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!