问题
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