yii2.0.46批量删除需结合console命令、文件日志与数据库日志表:用cleanupcontroller封装逻辑,分批处理并记录删除数量、条件、时间等信息,确保可追溯与审计安全。

在 Yii2.0.46 中做批量删除时加日志,核心是把删除动作、数量、条件、时间等关键信息记录下来,便于追溯和审计。推荐用 console 命令 + 文件日志 + 数据库日志表 三者结合,既安全又可查。
用 console 命令封装删除逻辑并写日志
避免在 Web 请求里执行批量删,改用控制台命令(如 CleanupController),天然支持长运行和日志输出:
- 在命令中调用
$this->stdout()输出到控制台,同时重定向到日志文件(crontab 配置时加上>> /path/to/cleanup.log 2>&1) - 使用 Yii 日志组件写入文件:
\Yii::info("Deleted {$count} cancelled orders older than {$days} days", 'cleanup') - 确保日志通道已配置(
config/console.php中的'log' => [...]含FileTarget)
数据库记录操作日志(推荐持久化)
建一张 admin_log 或 cleanup_log 表,每次批量删前/后插入一条记录:
- 字段建议含:
action(如 'delete_orders')、table_name、where_condition(JSON 或简写,如 "status='cancelled' AND created_at affected_rows、operator(如 'console')、created_at - 代码中插入日志示例:
$logData = [
'action' => 'delete_orders',
'table_name' => 'order',
'where_condition' => "status='cancelled' AND created_at 'affected_rows' => $count,
'operator' => 'console',
'created_at' => time(),
];
\Yii::$app->db->createCommand()->insert('cleanup_log', $logData)->execute();
?>
删除过程分批 + 每批单独记日志
大表删除不能一气呵成,否则事务过大、锁表久、失败难恢复。每批处理完都记一行日志:
- 用
array_chunk($ids, 1000)分批,每批执行createCommand()->delete() - 每批后写日志:
\Yii::info("Batch deleted {$batchCount} records (IDs: {$firstId}-{$lastId})", 'cleanup') - 配合
usleep(10000)小休眠,降低 DB 压力,也让日志时间戳有区分度
日志级别与敏感信息处理
生产环境注意日志内容安全:
- 不记录完整 SQL 或用户隐私字段(如手机号、邮箱),可用摘要或脱敏后写入(如
substr($phone, 0, 3) . '****' . substr($phone, -4)) - 用
Yii::info()记常规流程,Yii::error()记失败异常,Yii::warning()记跳过或部分失败 - 定期轮转日志(通过
FileTarget::maxFileSize和maxLogFiles控制)











