setHelp('该命令将查询 crm_customer 表中 sn 不为空的记录,并根据 sn 在 inquiry_log 表中查找对应的 order_no 记录,将 inquiry_log 的 created_at 更新到 crm_customer 的 created_at 字段');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$output->writeln('开始更新 crm_customer 的 created_at 字段...');
try {
// 使用事务确保数据一致性
DB::transaction(function () use ($output) {
// 查询所有 sn 字段不为空的客户记录
$customers = Db::table('crm_customer')
->where('sn', '<>', '')
->whereNotNull('sn')
->get(['id', 'sn']);
$output->writeln(''.count($customers).'');
$updatedCount = 0;
foreach ($customers as $customer) {
// 查找匹配的 inquiry_log 记录
$inquiryLog = Db::table('inquiry_log')
->where('order_no', $customer->sn)
->first(['r_time','created_at']);
// 如果找到匹配记录,则更新客户的 created_at 字段
if ($inquiryLog && isset($inquiryLog->r_time)) {
$created_at = $inquiryLog->r_time?:$inquiryLog->created_at;
DB::table('crm_customer')
->where('id', $customer->id)
->update(['created_at' => $created_at]);
$updatedCount++;
$output->writeln("已更新客户 ID {$customer->id} 的 created_at 为: {$created_at}");
}
}
$output->writeln("更新完成,总共更新了 {$updatedCount} 条记录。");
});
return self::SUCCESS;
} catch (\Exception $e) {
$output->writeln('执行过程中发生错误: ' . $e->getMessage() . '');
return self::FAILURE;
}
}
}