[英]How to change constraint FOREIGN KEY in mysql 8 from `ON DELETE CASCADE` to `ON DELETE SET NULL` in laravel migration or raw sql
首先,我的英语很差。 对于那个很抱歉。
我在cards
表中有一个外键,例如:
$table->foreignId('wallet_id')->constrained('wallets', 'id')->onDelete('cascade');
由于某些原因,我需要更改cascade
以在该列上set null
我尝试过(在新的迁移中):
$table->dropForeign('cards_wallet_id_foreign');
$table->foreignId('wallet_id')
->nullable()
->onDelete('set null')
->change();
运行正常,但删除时未设置 null:((
我该如何解决。 谢谢!!
您必须在新迁移中更改表迁移架构,并确保将外键字段设置为可为空:
$table->integer('wallet_id')->unsigned()->nullable();
然后像这样使用set null
:
$table->...->onDelete('set null');
如果要首先更改FOREIGN KEY约束,则需要删除外键的先前索引并仅将外键约束重新添加到列。
尝试这个:
Schema::table('cards', function (Blueprint $table) {
//Drop Previous Index
$table->dropForeign('cards_wallet_id_foreign');
//Since we want to set null on Delete Or Update
$table->unsignedBigInteger('wallet_id')->nullable()->change();
//Adding Only Forign key Constraints to column
//calling foreignId will re attempt to create a column
$table->foreign('wallet_id')->references('id')->on('wallets')->onDelete('set null')->onUpdate('set null')->change();
});
你不能只修改现有的迁移,你需要再做一个
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ChangeSomeTableColumn extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('the_table_you_are_changing', function (Blueprint $table) {
$table
->foreignId('wallet_id')
->constrained('wallets', 'id')
->onDelete('set null')
->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
}
}
经过多次收集和尝试,我找到了最好的解决方案(不需要drop column)
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AlterWalletIdColumnInCardsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('cards', function (Blueprint $table) {
$table->dropForeign('cards_wallet_id_foreign');
$table->foreignId('wallet_id')
->nullable()
->change();
$table->foreign('wallet_id')
->on('wallets')
->references('id')
->onDelete('set null');
});
}
/**
* I recommend you don't use down (laravel 9 will remove it as default
* migration)
*/
public function down()
{
Schema::table('cards', function (Blueprint $table) {
$table->dropForeign('cards_wallet_id_foreign');
$table->foreignId('wallet_id')
->nullable(false)
->change();
$table->foreign('wallet_id')
->on('wallets')
->references('id')
->onDelete('cascade');
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.