Skip to content

Commit

Permalink
联动删除
Browse files Browse the repository at this point in the history
  • Loading branch information
summerblue committed Mar 7, 2022
1 parent c228771 commit c52960a
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions database/migrations/2022_03_07_223818_add_references.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

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

return new class 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 c52960a

Please sign in to comment.