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

本文介绍了一种使用Yii框架批量更新数据库表中多个字段的方法,通过使用内置的createCommand()方法提高效率,尤其适用于需要更新大量数据的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们有时候需要更新一个表里面很多字段但是,用循环更新可能几个还算适用。但是一旦数据量几千个或者上万就不现实了,效率太低。
我们找到如下内置方法:
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值