如何修改外键coinstraint以删除级联

时间:2015-08-24 01:38:02

标签: php mysql laravel laravel-5

基本上,我已为 child

创建了此迁移
 // ...
 $table->integer('project_id')->unsigned();
 $table->primary('project_id');
 $table->foreign('project_id')->references('id')->on('project');
 // ...

但我忘了加onDelete('cascade')。我如何更新此迁移以添加它?

1 个答案:

答案 0 :(得分:2)

迁移应该描述对数据库的增量更改,以便可以对数据库模式进行版本控制。 不应更改过去的迁移,但如果需要进行任何更改,则应创建一个新的迁移文件,以应用必要的更改。

在您的情况下,您需要一个新的迁移文件,该文件将删除旧的约束定义并应用新的约束定义。以下将解决这个问题:

<?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');
     });
  }
}