我们有时候需要更新一个表里面很多字段但是,用循环更新可能几个还算适用。但是一旦数据量几千个或者上万就不现实了,效率太低。
我们找到如下内置方法:
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();
返回的是更新行数
这样我们就能批量的更新多条数据了,或者单独写更新SQL。
关键字词: