简体   繁体   中英

How to update table field = field+1 in laravel eloquent update query

I want to update a query in laravel where $field = $field+1 . It works fine using mysqli_query . But It is not working laravel orm.

I want to run this query in laravel orm

$sql = "Update $tbl set cnt=cnt+1 where user_id='x'"

When running this query in mysql I get following results

If cnt =1 in databases it will increment $cnt = $cnt+1 = 1+1 =2

I want to run this sql query in laravel orm

$where = ['user_id' => 'x'];
$field = ['cnt' => 'cnt+1'];
$tbl = 'log_cnt';
Capsule::table($tbl)->where($where)->update($field);

But After running this query output will show $cnt=0 in database

Incrementing or decrementing a value of a column

To increment single column

Capsule::table('log_cnt')->increment('cnt');
     Query: UPDATE log_cnt SET cnt = cnt + 1;

Capsule::table('log_cnt')->increment('cnt', 5);
     Query: UPDATE log_cnt SET cnt = cnt + 5;

To decrement single column

Capsule::table('log_cnt')->decrement('cnt');
     Query: UPDATE log_cnt SET cnt = cnt - 1;

Capsule::table('log_cnt')->decrement('cnt', 5);
     Query: UPDATE log_cnt SET cnt = cnt - 5;

You may also specify additional columns to update:

Capsule::table('log_cnt')->increment('cnt', 1, ['user_id' => 'x']);
    Query: UPDATE log_cnt SET cnt = cnt + 1, user_id = 'x';

Reference : https://laravel.com/docs/5.4/queries#increment-and-decrement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM