首先,我的英語很差。對于那個很抱歉。
我在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();
運行 oky 但洗掉時它沒有設定為 null :((
我該如何解決。謝謝!!
uj5u.com熱心網友回復:
你不能只修改現有的遷移,你需要再做一個
<?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()
{
}
}
uj5u.com熱心網友回復:
您必須在新遷移中更改表遷移架構,并確保將外鍵欄位設定為可為空:
$table->integer('wallet_id')->unsigned()->nullable();
然后set null像這樣使用:
$table->...->onDelete('set null');
uj5u.com熱心網友回復:
如果您想首先更改FOREIGN KEY Constraints,您需要洗掉外鍵的先前索引并僅將 Forign key Constraints 添加到列。
試試這個:
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();
});
uj5u.com熱心網友回復:
經過多次收集和嘗試,我找到了最佳解決方案(不需要洗掉列)
<?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');
});
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/381835.html
上一篇:我正在嘗試在我的Laravel8應用程式中上傳個人資料圖片。但是,我不斷收到“嘗試讀取陣列上的屬性“影像””錯誤
