当前位置: 代码迷 >> 综合 >> yii2.0 批量更新的封装(觉得解决了问题不妨点个赞关注下)
  详细解决方案

yii2.0 批量更新的封装(觉得解决了问题不妨点个赞关注下)

热度:108   发布时间:2023-11-10 19:09:15.0
    /*** note: 原生sql批量更新封装* @param $primaryKeyField            主键字段名* @param $data                       更新的数据,二维数组* @param string $updateFieldValue    更新的字段,一维数组* @param string $table 表名* @return mixed*/public function batchUpdate($primaryKeyField, $data, $updateFieldValue = '', $table = ''){$table = empty($table) ? self::tableName() : $table;$updateFieldValue = empty($updateFieldValue) ? array_keys($data[0]) : $updateFieldValue;$ids = implode(",", array_column($data, $primaryKeyField));$sqlHead = "UPDATE `{$table}` SET ".' ';$sqlEnd = "WHERE {$primaryKeyField} in ({$ids})";$sqlMiddle = '';foreach ($updateFieldValue as $k => $v) {$condition = '';foreach ($data as $key) {$condition .= "WHEN {$key[$primaryKeyField]} THEN '{$key[$v]}' ";}$sqlMiddle .= "{$v} = CASE {$primaryKeyField} {$condition} END,";}$sql = $sqlHead . rtrim($sqlMiddle, ',') . ' '.$sqlEnd;$res = \Yii::$app->db_aofei_activity->createCommand($sql)->execute();
}

也可以参考这两篇文章自己封装一个:

https://blog.csdn.net/weixin_42290280/article/details/89384741

https://blog.csdn.net/iteratorv2/article/details/103905511