Meddie
Meddie

Reputation: 557

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

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

Upvotes: 19

Views: 25400

Answers (4)

utsav
utsav

Reputation: 622

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

Upvotes: 8

Sajjad Ashraf
Sajjad Ashraf

Reputation: 3844

This worked fine for me

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

Upvotes: 3

Cyrec
Cyrec

Reputation: 455

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

Upvotes: -2

rmobis
rmobis

Reputation: 27002

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

Upvotes: 51

Related Questions