簡體   English   中英

如何將外鍵coinstraint修改為刪除級聯

[英]How modify foreign key coinstraint to on delete cascade

基本上,我已經為我的表創建了此遷移

 // ...
 $table->integer('project_id')->unsigned();
 $table->primary('project_id');
 $table->foreign('project_id')->references('id')->on('project');
 // ...

但是我忘了包括onDelete('cascade') 我如何更新此遷移以添加它?

遷移應該描述對數據庫的增量更改,以便可以對數據庫架構進行版本控制。 不應更改過去的遷移 ,但如果需要進行任何更改,則應創建一個將應用必要更改的新遷移文件。

在您的情況下,您需要一個新的遷移文件,該文件將刪除舊的約束定義並應用新的約束定義。 以下將解決問題:

<?php

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

class AddOnCascadeToProjectId extends Migration
{
  public function up()
  {
    Schema::table('your_table', function (Blueprint $table) {
      //drop the old constraint
      $table->dropForeign('your_table_project_id_foreign');
      //create new constraint with ON CASCADE
      $table->foreign('project_id')->references('id')->on('project')->onDelete('cascade');
    });
  }

  public function down()
  {
     Schema::table('your_table', function (Blueprint $table) {
       //drop new constraint with ON CASCADE
       $table->dropForeign('your_table_project_id_foreign');
       //recreate the old constraint
       $table->foreign('project_id')->references('id')->on('project');
     });
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM