diff --git a/database/migrations/2019_09_20_122431_add_references.php b/database/migrations/2019_09_20_122431_add_references.php new file mode 100644 index 000000000..3261049d5 --- /dev/null +++ b/database/migrations/2019_09_20_122431_add_references.php @@ -0,0 +1,40 @@ +foreign('user_id')->references('id')->on('users')->onDelete('cascade'); + }); + + Schema::table('replies', function (Blueprint $table) { + + // 当 user_id 对应的 users 表数据被删除时,删除此条数据 + $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); + + // 当 topic_id 对应的 topics 表数据被删除时,删除此条数据 + $table->foreign('topic_id')->references('id')->on('topics')->onDelete('cascade'); + }); + } + + public function down() + { + Schema::table('topics', function (Blueprint $table) { + // 移除外键约束 + $table->dropForeign(['user_id']); + }); + + Schema::table('replies', function (Blueprint $table) { + $table->dropForeign(['user_id']); + $table->dropForeign(['topic_id']); + }); + + } +}