最新版本
This commit is contained in:
77
app/command/SyncData.php
Normal file
77
app/command/SyncData.php
Normal file
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\command;
|
||||
|
||||
use think\console\Command;
|
||||
use think\console\Input;
|
||||
use think\console\Output;
|
||||
use think\facade\Db;
|
||||
|
||||
class SyncData extends Command
|
||||
{
|
||||
protected function configure()
|
||||
{
|
||||
$this->setName('syncdata')->setDescription('从宝塔同步并处理数据');
|
||||
}
|
||||
|
||||
protected function execute(Input $input, Output $output)
|
||||
{
|
||||
$output->writeln('开始连接远程数据库...');
|
||||
|
||||
try {
|
||||
// 增加 count 确认远程到底有没有数据
|
||||
$total = Db::connect('remote')->table('tickets')->count();
|
||||
$output->writeln("远程表共有 {$total} 条数据待处理");
|
||||
|
||||
if ($total == 0) {
|
||||
$output->writeln('警告:远程表中没有找到数据,请检查表名或权限。');
|
||||
return 0;
|
||||
}
|
||||
|
||||
// chunk(100) 比较平衡,2 太小了
|
||||
Db::connect('remote')->table('tickets')->chunk(100, function ($remoteRows) use ($output) {
|
||||
$processedData = [];
|
||||
|
||||
foreach ($remoteRows as $row) {
|
||||
$operator = Db::name('company_operators')->where('operator_name', $row['operator'])->find();
|
||||
|
||||
$operator_id = $operator ? $operator['id'] : null;
|
||||
$company_id = $operator ? $operator['company_id'] : null;
|
||||
|
||||
|
||||
$processedData[] = [
|
||||
// 'id' => $row['id'], // 如果想用旧ID就取消注释,否则留空让本地表自增
|
||||
'website' => $row['website_url'],
|
||||
'datanum' => $row['datanum'],
|
||||
'create_time' => !empty($row['create_time']) ? strtotime($row['create_time']) : 0,
|
||||
'update_time' => !empty($row['update_time']) ? strtotime($row['update_time']) : 0,
|
||||
'progress' => $row['progress'],
|
||||
'remark' => $row['remark'] ?? '',
|
||||
'status' => $row['is_completed'],
|
||||
'lock_time' => $row['lock_time'] ?? 0,
|
||||
'operator_id' => $operator_id,
|
||||
'company_id' => $company_id,
|
||||
'user_id' => $row['staff_id'] ?? null,
|
||||
];
|
||||
}
|
||||
|
||||
if (!empty($processedData)) {
|
||||
// 使用 try-catch 捕获插入时的报错
|
||||
try {
|
||||
Db::name('tickets')->insertAll($processedData);
|
||||
$output->writeln("成功插入一批数据 (" . count($processedData) . " 条)");
|
||||
} catch (\Exception $e) {
|
||||
$output->writeln("本地插入失败: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (\Exception $e) {
|
||||
$output->writeln("严重错误: " . $e->getMessage());
|
||||
}
|
||||
|
||||
$output->writeln('--- 同步流程结束 ---');
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user