Skip to content

Commit

Permalink
Add foreign key references
Browse files Browse the repository at this point in the history
  • Loading branch information
summerblue committed Nov 1, 2017
1 parent b70dc5b commit 1b4fdd8
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions database/migrations/2017_11_01_165250_add_references.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddReferences extends Migration
{
public function up()
{
Schema::table('topics', function (Blueprint $table) {

// user_id 对应的 users 表数据被删除时删除词条
$table->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']);
});

}
}

0 comments on commit 1b4fdd8

Please sign in to comment.