Laravel 4:更新行时如何从列的当前值中减去一个


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

我想知道如何执行这样的事情:

Table::update(array('position'=>'position+1'));

据我所知,laravel 4 将"位置+1"处理为字符串,因此变为 0。

我想执行类似

UPDATE table SET position = position + 1

我可以用口才来做到这一点吗?

编辑:没关系,哎呀.."DB::table('users')->increment('votes');"

只需使用 increment 方法:

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

这同样适用于decrement

DB::table('users')->decrement('rank');

您甚至可以将第二个参数设置为要添加/减去的量:

DB::table('users')->increment('posts', 5);
DB::table('users')->decrement('likes', 3);

此外,如果您需要随之更新其他列,请将其作为第三个参数传递:

DB::table('users')->increment('range', 3, array(
    'name' => 'Raphael',
    'rank' => 10
));

Eloquent模型也是如此:

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

你也可以像这样使用DB::raw方法:

DB::table('tablename')->where(your condition)->update(['position' => DB::raw('position+1')]);

你也可以用这个做其他操作,比如

DB::table('tablename')->where(your condition)->update(['position' => DB::raw('position * 2')]);

对我来说很好用

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

简单地说,你可以像这样使用 DB::raw 方法: Table::update(DB::raw('position=position+1'));