allocatr/application/admin/command/ImportServiceItems.php
2025-03-23 18:19:34 +08:00

73 lines
2.2 KiB
PHP

<?php
namespace app\admin\command;
use Overtrue\Pinyin\Converter;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use Overtrue\Pinyin\Pinyin;
class ImportServiceItems extends Command
{
protected function configure()
{
$this->setName('item:import:new')
->setDescription('倒入 item 数据');
}
protected function execute(Input $input, Output $output)
{
// 读取 JSON 文件
$jsonFile = __DIR__.'/newItem.json'; // JSON 文件路径
if (!file_exists($jsonFile)) {
$output->writeln("JSON file not found.");
return;
}
$jsonData = file_get_contents($jsonFile);
$data = json_decode($jsonData, true);
if (json_last_error() !== JSON_ERROR_NONE) {
$output->writeln("Invalid JSON format.");
return;
}
// 调用递归函数导入数据
$this->importData($data['服务项目'],$output, 0, 1);
$output->writeln("Data import completed.");
}
// 递归函数处理服务项插入
protected function importData($items,Output $output, $parentId = 0, $level = 1)
{
foreach ($items as $item) {
// 插入当前服务项
$insertData = [
'pid' => $parentId,
'level' => $level,
'title' => $item['title'],
'key_word' => null, // 可以根据需要提供关键词
'image' => null, // 可以根据需要提供图标
'sort' => 0, // 可以根据需要设置排序
'status' => 1, // 默认启用
];
// 执行插入
$result = Db::name('item')->insert($insertData);
if ($result) {
$output->writeln("Inserted: " . $item['title']);
} else {
$output->writeln("Failed to insert: " . $item['title']);
}
// 如果有子项,递归插入
if (isset($item['children'])) {
$this->importData($item['children'], $output,Db::name('item')->getLastInsID(), $level + 1);
}
}
}
}