有一些类别(类别迁移文件)
public function up():void
{
Schema::create('blog_categories', static function (Blueprint $table) {
$table->id();
$table->bigInteger('parent_id')->unsigned()->default(1);
$table->string('slug')->unique();
$table->string('title');
$table->text('description')->nullable();
$table->timestamps();
$table->softDeletes();
});
}
所有这些类别都与帖子相关联(迁移后文件)
public function up(): void
{
Schema::create('blog_posts', static function (Blueprint $table) {
$table->id();
$table->bigInteger('category_id')->unsigned();
$table->bigInteger('user_id')->unsigned();
$table->string('slug')->unique();
$table->string('title');
$table->text('excerpt')->nullable();
$table->string('tdk_title')->nullable();
$table->text('tdk_description')->nullable();
$table->text('tdk_keywords')->nullable();
$table->text('content_raw');
$table->text('content_html');
$table->integer('view_count')->default(0);
$table->boolean('is_published')->default(false);
$table->timestamp('published_at')->nullable();
$table->timestamps();
$table->softDeletes();
$table->index('is_published');
//FK
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('category_id')
->references('id')
->on('blog_categories')
->onDelete('cascade');
});
}
需要解决两个任务:
- 防止删除根类别。这没有问题,在 destroy() 中检查 id,如果匹配则返回错误消息。
- 删除类别并将所有相关帖子移至根目录。在这里我停滞不前了,如何正确实现它?

我将执行以下操作:模型中的 1 将描述连接:
2 删除目录时会得到它的所有帖子:
3 好吧,我会更新每个帖子。然后删除类别。