allocatr/application/common/command/ImportArea.php
2025-07-15 12:42:26 +08:00

82 lines
2.9 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\common\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
class ImportArea extends Command
{
protected function configure()
{
$this->setName('import:area')
->setDescription('导入港澳台行政区域数据到 fa_area 表');
}
protected function execute(Input $input, Output $output)
{
// 区域数据(来自你提供的 JSON
$areaData = json_decode(file_get_contents(__DIR__ . '/area.json'), true);
Db::startTrans();
$out = [];
try {
foreach ($areaData as $parentCode => $children) {
foreach ($children as $code => $name) {
if (strlen(rtrim($parentCode, '0')) == 2) {
// 省 -> 市Level 2
$provinceCode = $parentCode;
$level = 2;
$shortMergeName = $name;
$data = [
'code' => rtrim($code, "0"),
'name' => $name,
'short_name' => $name,
'merge_name' => $name,
'short_merge_name' => $shortMergeName,
'level' => $level,
'province_code' => rtrim($provinceCode, "0"),
'city_code' => rtrim($code, "0"),
'area_code' => rtrim($code, "0"),
'pinyin' => '',
'abbr' => ''
];
$out[] = $data;
// dd($data);
} else {
// 市 -> 区Level 3
$data = [
'code' => rtrim($code, '0'),
'name' => $name,
'short_name' => $name,
'merge_name' => $areaData[substr($parentCode, 0,2) . '0000'][$parentCode] . '/' . $name,
'short_merge_name' => $name,
'level' => 3,
'province_code' => rtrim($parentCode, '0'),
'city_code' => rtrim($code, '0'),
'area_code' => rtrim($code, '0'),
'pinyin' => '',
'abbr' => ''
];
$out[] = $data;
// dd($data);
}
}
}
Db::table('fa_areas')->insertAll($out);
Db::commit();
$output->writeln("<info>港澳台区域数据导入成功!</info>");
} catch (\Throwable $e) {
Db::rollback();
throw $e;
$output->writeln("<error>导入失败:" . $e->getMessage() . "</error>");
}
}
}