Files
2026-08-08 18:27:38 +08:00

81 lines
2.8 KiB
PHP

<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
/**
* PD 站点内容种子:把随包发布的真实内容(分类/产品/文章/术语)灌入数据库。
* 数据来源:database/seeders/data/site_content.json(由本地 MySQL 导出,含 20 篇 PD 技术文章 + 8 原创 + 10 转载 + 3 产品 + 5 术语 + 6 分类)。
*
* 设计要点:
* - 全部按 slug 幂等(已存在则跳过),可重复执行,不会覆盖用户后续新增/修改的内容。
* - 分类用「原 id -> 新 id」slug 映射,跨库部署 id 错位也无妨。
* - 文章作者统一关联到 admin@cloud-chip.cn 账户(author 文本字段仍保留原作者署名)。
*/
class PdContentSeeder extends Seeder
{
public function run(): void
{
$path = __DIR__ . '/data/site_content.json';
if (! file_exists($path)) {
return;
}
$data = json_decode(file_get_contents($path), true);
if (! is_array($data)) {
return;
}
// 1. 分类:按 slug 幂等,建立 原id -> 新id 映射(跨库 id 对齐)
$catMap = [];
foreach ($data['categories'] ?? [] as $c) {
$origId = $c['id'];
$existing = DB::table('categories')->where('slug', $c['slug'])->first();
if ($existing) {
$newId = $existing->id;
} else {
$row = $c;
unset($row['id']);
$newId = DB::table('categories')->insertGetId($row);
}
$catMap[$origId] = $newId;
}
// 文章作者关联到 admin 账户(若已存在)
$adminId = DB::table('users')->where('email', 'admin@cloud-chip.cn')->value('id');
// 2. 产品
foreach ($data['products'] ?? [] as $p) {
if (DB::table('products')->where('slug', $p['slug'])->exists()) {
continue;
}
if (! empty($p['category_id'])) {
$p['category_id'] = $catMap[$p['category_id']] ?? null;
}
DB::table('products')->insert($p);
}
// 3. 文章
foreach ($data['articles'] ?? [] as $a) {
if (DB::table('articles')->where('slug', $a['slug'])->exists()) {
continue;
}
if (! empty($a['category_id'])) {
$a['category_id'] = $catMap[$a['category_id']] ?? null;
}
$a['user_id'] = $adminId; // 弱关联;author 文本字段保留真实署名
DB::table('articles')->insert($a);
}
// 4. 术语库
foreach ($data['glossary_terms'] ?? [] as $g) {
if (DB::table('glossary_terms')->where('slug', $g['slug'])->exists()) {
continue;
}
DB::table('glossary_terms')->insert($g);
}
}
}