【问题标题】:Laravel query builder mass update - sum current value + another valueLaravel query builder mass update - 求和当前值 + 另一个值
【发布时间】:2022-11-28 23:21:23
【问题描述】:

我知道我们可以使用 Laravel 查询生成器使用它的 update() 方法进行批量更新:

DB::table('my_table')
    ->where('created_at', '>=', '2000-01-01')
    ->update(['column' => 10]);

这将等同于此查询:

UPDATE my_table SET column = 10 WHERE created_at >= '2000-01-01' 

如果我想将该列的值增加 10,而不是设置一个固定值怎么办?

这就是我的意思,在 SQL 中:

UPDATE my_table SET column = column + 10 WHERE created_at >= '2000-01-01'

【问题讨论】:

    标签: php laravel laravel-query-builder


    【解决方案1】:

    您可以简单地使用 Db::raw 方法:

    DB::table('my_table'
      ->where('created_at', '>=', '2000-01-01')
      ->update([
        'column'=> DB::raw('column+10'), 
      ]);
    

    更多资讯:https://laravel.com/docs/9.x/queries#raw-expressions

    其他解决方案,使用增量法(https://laravel.com/docs/9.x/queries#increment-and-decrement):

    DB::table('my_table')
       ->where('created_at', '>=', '2000-01-01')
       ->increment('column', 10);
    

    【讨论】:

      猜你喜欢
      • 2022-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-15
      • 2017-10-08
      • 1970-01-01
      • 2021-08-04
      • 2020-11-29
      相关资源
      最近更新 更多