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
*/

Yii::$app->db->createCommand()->update(Chat::tableName(), ['user_read' => '1'], 'guid_id=' . $roomResult['pid'])->execute();

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