在 Laravel 的现有栏目中添加“ ON DELETE CASCADE”

我的表中有 user _ id fk 列

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

我应该添加 级联删除功能到这个现有的专栏。我如何做到这一点?

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

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);'
);
}
$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也必须是无符号的。

首先放置外键。感谢 剃刀的提示

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

谢谢你的回答。帮我找到 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();
});
}

在我的示例中,我需要将 colname 放入一个数组 else 中,这将是一个错误。

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

Mysql 5.7版本

在当前迁移中对 user_id使用无符号函数:

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

小代码

$table->foreignId('user_id')->constrained('users');

laravel 7.0开始,你可以使用 $table->foreignId('user_id');,它是 $table->unsignedBigInteger('user_id');的别名

因此,我们的一线解决方案,使外键列删除级联如下:

$table->foreignId('user_id')->constrained('users')->onDelete('cascade');