2016-03-27 237 views
1

我嘗試在遷移中添加外鍵約束。出於某種原因,當我將它設置爲可爲空時,它確實有效,但當它使其不可空時它不起作用。爲什麼會發生這種情況,我該如何解決這個問題?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)

回答

2

的遷移發生在你的文件名指定的順序。也許你的角色表在這次遷移運行的時候還沒有創建,你的數據庫抱怨嘗試引用(還)不存在的表中的字段?

例如:添加溶液:2016_03_27_0000_first將前2016_03_28_0000_second

UPDATE被執行。

我注意到你有「onDelete('set null')」字段,你試圖設置爲不可爲空。如果該角色被刪除,那麼也會導致問題,因爲它會嘗試將該值設置爲空。

應設置兩個外鍵:

->onDelete('cascade') 

這樣,如果用戶或角色被刪除,與之相關的任何關聯也會自動被刪除而不是簡單地設置爲空或左掛。

乾杯

+0

我想到了這一點,並把它放在正確的順序,但仍然無法正常工作。有點慚愧,這個sql一般錯誤有很多可能出錯的東西 – Markinson

+1

哦,我剛剛注意到你也有'onDelete('set null');'你試圖設置爲非索引字段-nullable。如果該角色被刪除,這也會導致問題,並且級聯到嘗試將其設置爲空的該條目。也許你應該試着將兩個外鍵都設置爲' - > onDelete('cascade');'這樣如果用戶或角色被刪除,任何與它們相關的關聯也會被刪除。 –

+0

好的!我會嘗試一下,讓你知道它是否會很快奏效。 – Markinson

相關問題