我嘗試在遷移中添加外鍵約束。出於某種原因,當我將它設置爲可爲空時,它確實有效,但當它使其不可空時它不起作用。爲什麼會發生這種情況,我該如何解決這個問題?Laravel - 1215無法添加外鍵約束
這並不工作:
Schema::create('role_user', function (Blueprint $table){
$table->increments('id');
$table->integer('role_id')->unsigned()->index()->nullable();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('set null');
$table->integer('user_id')->unsigned()->index()->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('set null');
$table->timestamps();
});
這引發異常:
Schema::create('role_user', function (Blueprint $table){
$table->increments('id');
$table->integer('role_id')->unsigned()->index();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('set null');
$table->integer('user_id')->unsigned()->index()->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('set null');
$table->timestamps();
});
無論是角色和用戶表使這些限制之前已經excist。我希望它們不能爲空(所以它們必須被填充)。錯誤:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table role_user add constraint role_user_role_id_foreign foreign key (role_id) references roles (id) on delete set null)
我想到了這一點,並把它放在正確的順序,但仍然無法正常工作。有點慚愧,這個sql一般錯誤有很多可能出錯的東西 – Markinson
哦,我剛剛注意到你也有'onDelete('set null');'你試圖設置爲非索引字段-nullable。如果該角色被刪除,這也會導致問題,並且級聯到嘗試將其設置爲空的該條目。也許你應該試着將兩個外鍵都設置爲' - > onDelete('cascade');'這樣如果用戶或角色被刪除,任何與它們相關的關聯也會被刪除。 –
好的!我會嘗試一下,讓你知道它是否會很快奏效。 – Markinson