Yii2 使用批量更新数据库字段方法非循环更新

我们有时候需要更新一个表里面很多字段但是,用循环更新可能几个还算适用。但是一旦数据量几千个或者上万就不现实了,效率太低。
我们找到如下内置方法:
Yii::$app->db->createCommand()->update($table, $columns, $condition = '')->execute();
第一个是表,第二个修改字段 ,第三个是条件
方法说明如下:
/**
* Creates an UPDATE command.
* For example,
*
* ~~~
* $connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();
* ~~~
*
* The method will properly escape the column names and bind the values to be updated.
*
* Note that the created command is not executed until [[execute()]] is called.
*
* @param string $table the table to be updated.
* @param array $columns the column data (name => value) to be updated.
* @param string|array $condition the condition that will be put in the WHERE part. Please
* refer to [[Query::where()]] on how to specify condition.
* @param array $params the parameters to be bound to the command
* @return $this the command object itself
*/
Yii2 使用批量更新数据库字段方法非循环更新_第1张图片
Yii::$app->db->createCommand()->update(Chat::tableName(), ['user_read' => '1'], 'guid_id=' . $roomResult['pid'])->execute();

返回的是更新行数
原文地址:https://www.apizl.com/archives/view-134227-1.html

你可能感兴趣的:(开发日常)