Files
useds/app/command/CustomerCodeCommand.php
T
2026-01-05 14:33:21 +08:00

62 lines
2.1 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace app\command;
use app\crm\model\Customer;
use support\Log;
use Symfony\Component\Console\Command\Command as SymfonyCommand;
use Webman\Console\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class CustomerCodeCommand extends SymfonyCommand
{
protected static $defaultName = 'customer:generate-code';
protected function configure()
{
$this->setDescription('为crm_customer表所有记录生成唯一code码,分批处理');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$batchSize = 1000;
$total = Customer::withTrashed()->where('code','')->count();
$output->writeln("总计需处理:$total 条记录");
$processed = 0;
do {
// 查询一批未生成code的记录
$customers = Customer::withTrashed()->where('code','')->limit($batchSize)->get();
if ($customers->isEmpty()) {
break;
}
// Eloquent 批量处理
foreach ($customers as $customer) {
// 生成唯一16位code,CM+14位
$unique = strtoupper(substr(md5($customer->id . microtime(true) . mt_rand(1000, 9999)), 0, 14));
$code = 'CM' . $unique;
// 防止极小概率重复
while (Customer::where('code', $code)->exists()) {
$unique = strtoupper(substr(md5($customer->id . microtime(true) . mt_rand(1000, 9999)), 0, 14));
$code = 'CM' . $unique;
}
$created_at = $customer->created_at->getTimestamp();
$obtain = $created_at > strtotime('2025-07-29')?$created_at:strtotime('2025-07-29');
$customer->code = $code;
$customer->obtain = $obtain;
$customer->save();
$processed++;
}
$output->writeln("已处理:$processed / $total");
} while (true);
$output->writeln('<info>全部处理完成!</info>');
return self::SUCCESS;
}
}