添加" ON DELETE CASCADE"到Laravel的现有专栏

时间:2014-11-08 18:49:35

标签: php laravel laravel-4 database-migration

我的表格中有user_id fk列

$table->foreign('user_id')->references('id')->on('users');

我应该在现有列上添加级联删除功能。我怎么能这样做?

7 个答案:

答案 0 :(得分:58)

首先删除外键。感谢Razor获得此提示

$table->dropForeign('answers_user_id_foreign');
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');

答案 1 :(得分:4)

Laravel模式构建器无法修改当前状态的列,因此您将使用原始查询。您将不得不删除并重新创建约束

<强>的PostgreSQL

function up()
{
    DB::statement('alter table answers drop constraint answers_user_id_foreign,
                   add constraint answers_user_id_foreign
                   foreign key (user_id)
                   references users(id)
                   on delete cascade;'
    );
}
function down()
{
    DB::statement('alter table answers drop constraint answers_user_id_foreign,
                   add constraint answers_user_id_foreign
                   foreign key (user_id)
                   references users(id);'
    );
}

<强>的MySQL

function up()
{
    DB::statement('alter table answers drop FOREIGN KEY answers_user_id_foreign;');
    DB::statement('alter table answers add constraint answers_user_id_foreign
                   foreign key (user_id)
                   references users(id)
                   on delete cascade;'
    );
}
function down()
{
    DB::statement('alter table answers drop FOREIGN KEY answers_user_id_foreign;');
    DB::statement('alter table answers add constraint answers_user_id_foreign
                   foreign key (user_id)
                   references users(id);'
    );
}

答案 2 :(得分:2)

感谢您的回答。帮助我在L5.1中找到这个工作代码:

public function up()
{
    Schema::table('transactions', function (Blueprint $table) {
        $table->dropForeign('transactions_order_id_foreign');
        $table->foreign('order_id')
            ->references('id')->on('orders')
            ->onDelete('cascade')
            ->change();
    });

    Schema::table('orders', function (Blueprint $table) {
        $table->dropForeign('orders_user_id_foreign');
        $table->foreign('user_id')
            ->references('id')->on('users')
            ->onDelete('cascade')
            ->change();
    });
}

答案 3 :(得分:2)

就我而言,我需要将col名称放在一个数组中,否则会出错。

@TestInstance

mysql 5.7 ver

答案 4 :(得分:1)

$table->foreign('user_id')
      ->references('id')->on('users')
      ->onDelete('cascade');

答案 5 :(得分:0)

$table->integer('user_id')->unsigned();    
$table->foreign('user_id')
      ->references('id')->on('users')
      ->onDelete('cascade');

我假设你使用Illuminate\Database\Schema\Blueprint::primary()来创建users.id。如果是这种情况,那么users.id将是未签名的。因此,您的外键列user_id也必须是未签名的。

答案 6 :(得分:0)

在当前迁移中,将无符号函数用于user_id

$table->interger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('table_name')->onDelete('cascade');