前言:
在使用 Laravel8 的查询构造器来进行数据库查询的时候,往往需要将某个字段加减1,或者加减n,这个时候可以使用自带的 increment() | decrement() 接口,但是如果想使用 update() 接口的时候就不能和 increment() | decrement() 接口同时使用,所以字段加减需要使用原生语句。
代码:
class test
{
// 数据库表名
const TABLE_NAME = 'table_name';
public function test() : void
{
$condition = [['id', '1']];
// 传递参数时,使用原生语句 DB::raw(your_query);
$updateData = ['login_times' => DB::raw('login_times + 1')];
$result = DB::table(self::TABLE_NAME)
->where($condition)
->update($updateData);
}
}
如果不使用 DB::raw(); 语句,而直接使用 key = key + 1 会出现
A non-numeric value encountered 错误。
例:
// 错误例
$updateData = ['login_times' => 'login_times' + 1];
// 正确例
$updateData = ['login_times' => DB::raw('login_times + 1')];