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
Yii2框架中,批量更新多个字段并且每个记录的更新条件各不相同通常涉及到使用`ActiveRecord`的`updateAll()`或`updateAllCount()`方法,结合`condition`参数来指定不同的更新规则。这里有一个简单的示例: ```php use Yii; use app\models\ModelName; // 替换为你实际模型的名称 // 假设我们有一个用户表User,我们想根据用户ID批量更新用户名和状态 $usersToUpdate = [ ['id' => 1, 'username' => 'new_username_1', 'status' => User::STATUS_ACTIVE], // 更新ID为1的用户 ['id' => 2, 'username' => 'new_username_2', 'status' => User::STATUS_INACTIVE], // 更新ID为2的用户,设置状态为活动 ['id' => 3, 'username' => 'new_username_3'], // 只更新ID为3的用户的用户名,状态不做改变 ]; // 使用updateAll()方法 ModelName::updateAll([ 'username' => new Expression('CASE WHEN id IN (:ids) THEN :value ELSE username END'), 'status' => new Expression('CASE WHEN id IN (:ids) THEN :status ELSE status END'), ], [ ':ids' => array_keys($usersToUpdate), ':value' => function ($id) use ($usersToUpdate) { return $usersToUpdate[$id]['username']; }, ':status' => function ($id) use ($usersToUpdate) { return $usersToUpdate[$id]['status'] ?: User::STATUS_DEFAULT; } ]); // 或者使用updateAllCount()方法,如果只关心操作成功条数 $count = ModelName::updateAllCount([ 'username' => new Expression('CASE WHEN id IN (:ids) THEN :value ELSE username END'), 'status' => new Expression('CASE WHEN id IN (:ids) THEN :status ELSE status END'), ], [ ':ids' => array_keys($usersToUpdate), ':value' => function ($id) use ($usersToUpdate) { return $usersToUpdate[$id]['username']; }, ':status' => function ($id) use ($usersToUpdate) { return $usersToUpdate[$id]['status'] ?: User::STATUS_DEFAULT; } ]); // 如果你想了解哪些记录更新了,可以查看受影响的行数或者获取具体的更新结果 if ($count > 0) { echo "成功更新了 {$count} 条记录"; } else { echo "没有符合条件的数据需要更新"; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值