From 0116fc411665b8f6a905124bb62ec673e70e618c Mon Sep 17 00:00:00 2001 From: gouki Date: Mon, 7 Sep 2026 19:46:24 +0000 Subject: [PATCH] fix(import): create placeholder category for orphan articles --- app/Console/Commands/SablogImportCommand.php | 28 ++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/app/Console/Commands/SablogImportCommand.php b/app/Console/Commands/SablogImportCommand.php index d97ee01..8392983 100644 --- a/app/Console/Commands/SablogImportCommand.php +++ b/app/Console/Commands/SablogImportCommand.php @@ -213,6 +213,8 @@ class SablogImportCommand extends Command } } + $this->ensureCategoryExists((int) $row->cid); + $this->upsertWithId(Article::class, (int) $row->articleid, [ 'category_id' => (int) $row->cid, 'user_id' => (int) $row->uid, @@ -424,6 +426,32 @@ class SablogImportCommand extends Command return $model; } + /** @var array */ + protected array $ensuredCategories = []; + + /** + * 老库里可能存在已删除分类的孤儿文章,为其补一个占位分类以满足外键约束。 + */ + protected function ensureCategoryExists(int $cid): void + { + if ($cid <= 0 || isset($this->ensuredCategories[$cid])) { + return; + } + + $this->ensuredCategories[$cid] = true; + + if (Category::query()->whereKey($cid)->exists()) { + return; + } + + $this->upsertWithId(Category::class, $cid, [ + 'name' => "已删除分类 {$cid}", + 'display_order' => 9999, + 'articles_count' => 0, + ]); + $this->warn("Category #{$cid} missing in source; placeholder created for orphan articles."); + } + protected function countTable($source, string $table, string $key): void { if ($this->sourceTableExists($source, $table)) {