向现有迁移添加 cascade/delete 功能

Add cascade/delete functionality to existing migration

我的 database 中有 2 个 tables。一份用于 Courses,一份用于 Course Chapters

coursesmigration 看起来像这样:

Schema::create('courses', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->timestamps();
});

chaptersmigration 看起来像这样:

Schema::create('course_chapters', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedInteger('course_id');
    $table->timestamps();
});

我想要课程和章节cascade down,所以当我删除course时,chapter也会被删除。

我看到的一些例子利用删除 foreign key 但我从未将我的专栏签名为 foreign key

例如,通常情况下,我可以:

$table->dropForeign('course_id');

$table->foreign('course_id')
->references('id')->on('courses')
->onDelete('cascade');

我如何在(最好)new migration 中完成此操作以及我应该在什么 table 上添加 foreign key

这应该继续你的 course_chapters table:

$table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');

您不需要添加 $table->dropForeign('course_id');,因为这将从列中删除外键。

注意:还有这个:

$table->unsignedInteger('course_id');

应该是这样的:

$table->unsignedBigInteger('course_id');

因为使用不同的数据类型会报错