1
0
Fork 0

更新 database/seeders/KeywordSeeder.php

panliang 2023-12-01 09:41:18 +08:00
parent 1b5d282363
commit 19ea8cfdf9
1 changed files with 33 additions and 25 deletions

View File

@ -3,6 +3,7 @@
namespace Database\Seeders; namespace Database\Seeders;
use App\Models\Keyword; use App\Models\Keyword;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder; use Illuminate\Database\Seeder;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
@ -10,44 +11,51 @@ class KeywordSeeder extends Seeder
{ {
/** /**
* Run the database seeds. * Run the database seeds.
*
* @return void
*/ */
public function run() public function run(): void
{ {
Keyword::truncate(); Keyword::truncate();
$list = [ $list = [
['key' => 'treat_type', 'name' => '诊疗类别', 'children' => [ ['key' => 'product_category', 'name' => '商品分类', 'children' => [
['key' => 'treat_head', 'name' => '头疗', 'content' => '按摩意见:', 'image' => url('images/treat_head.png')], ['name' => '家用电器', 'children' => [
['key' => 'treat_normal', 'name' => '看病', 'content' => '病症:', 'image' => url('images/treat_normal.png')], ['name' => '电视'],
['name' => '冰箱'],
['name' => '洗衣机'],
]],
['name' => '手机数码', 'children' => [
['name' => '手机'],
['name' => '手机配件'],
['name' => '摄影摄像'],
]],
['name' => '电脑办公', 'children' => [
['name' => '电脑整机'],
['name' => '外设产品'],
['name' => '网络产品'],
]]
]],
['key' => 'article_category', 'name' => '文章分类', 'children' => [
['name' => '后端'],
['name' => '前端'],
['name' => 'Android'],
['name' => 'IOS'],
['name' => '开发工具'],
['name' => '人工智能'],
]] ]]
]; ];
$this->createByTree($list); $this->createByTree($list);
} }
protected function createByTree($list, $parent = null) protected function createByTree($list, $parent = null)
{ {
$count = count($list);
foreach ($list as $index => $item) { foreach ($list as $index => $item) {
$key = data_get($item, 'key'); $params = Arr::except($item, ['children']);
if (! $key) { $params['sort'] = $index;
if (! $parent) { $params['parent_id'] = $parent ? $parent->id : 0;
throw new \Exception('key 必填'); $params['key'] = data_get($item, 'key', data_get($parent, 'key') . '_' . $index);
} $model = Keyword::create($params);
$key = $parent->key.'_'.($index + 1);
}
$attributes = [
'key' => $key,
'parent_id' => data_get($parent, 'id', 0),
'path' => ($parent ? $parent->path.$parent->id : '').'-',
'level' => data_get($parent, 'level', 0) + 1,
'sort' => $count - $index,
];
if ($id = data_get($item, 'id')) {
$attributes['id'] = $id;
}
$model = Keyword::create(array_merge($attributes, Arr::except($item, ['children'])));
if ($children = data_get($item, 'children')) { if ($children = data_get($item, 'children')) {
$this->createByTree($children, $model); $this->createByTree($children, $model);
} }