Reputation: 312
I have 2 tables
in my database
. One for Courses
and one for Course Chapters
.
The migration
for the courses
looks like this:
Schema::create('courses', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
});
The migration
for the chapters
looks like this:
Schema::create('course_chapters', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedInteger('course_id');
$table->timestamps();
});
I want the course and the chapter to cascade down
, so when i delete a course
, the chapter
also will be deleted.
Some examples i saw make use of deleting the foreign key
but I never signed my column as a foreign key
.
For example, normally, I could:
$table->dropForeign('course_id');
$table->foreign('course_id')
->references('id')->on('courses')
->onDelete('cascade');
How can i accomplish this in a (preferably) new migration
and on what table
should i add the foreign key
?
Upvotes: 1
Views: 1022
Reputation: 14278
This as it is should go on your course_chapters
table:
$table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
You don't need to add $table->dropForeign('course_id');
because that will drop the foreign key from the column.
NOTE: and this:
$table->unsignedInteger('course_id');
Should be this:
$table->unsignedBigInteger('course_id');
Because it will throw an error of using different data types.
Upvotes: 2