2015-10-21 245 views
0

我在運行遷移時遇到問題。我有一個MySQL數據庫與一些表。具體的表格是product_blender。表中的某些字段是這樣的:Laravel 5遷移 - 外鍵約束失敗

  • id (PK)
  • area_id (FK)
  • inhabitants (varchar)
  • heating_type_id (FK)
  • ...

現在我想創建一個名爲installateur_types另一個表。該表需要包含PKvarchar字段。我還想創建一個FKproduct_blender表中的我的新創建tabel

這是我做了什麼:

生成的遷移創建一個表:

public function up() 
{ 
    Schema::create('installateur_types', function(Blueprint $table) 
    { 
     $table->increments('id'); 
     $table->string('type'); 
    }); 
} 

public function down() 
{ 
    Schema::drop('installateur_types'); 
} 

運行遷移,這是成功的。表格是使用正確的字段創建的。

然後,我創建了遷移以將FK字段添加到product_blender表

public function up() 
{ 
    Schema::table('product_blenders', function ($table) { 
     $table->integer('installateurtype_id')->unsigned(); 
     $table->foreign('installateurtype_id')->references('id')->on('installateur_types')->onDelete('cascade'); 
    }); 
} 

public function down() 
{ 
    // 
} 

當我現在運行遷移我收到以下錯誤: enter image description here

我在做什麼錯?

+0

以前是否存在'product_blenders'表? – AndreL

回答

4

如果您的products_blender表不爲空,那麼當您添加一個不爲空的新列(這是默認的口才)時,它將自行假設一些默認值。該值可能不在此新列所指的表中,導致外鍵約束失敗。

其中之一來解決這個問題的辦法是給一個默認值到新列或只是使它可爲空

$table->integer('installateurtype_id')->unsigned()->nullable(); 
$table->foreign('installateurtype_id')->references('id')->on('installateur_types')->onDelete('cascade'); 

還有另外一個解決方案,它可關閉此檢查,其可以使用DB::statement('SET FOREIGN_KEY_CHECKS=0;')來完成。然後再次用DB::statement('SET FOREIGN_KEY_CHECKS=1;')轉動那個。在你的代碼中,你可以做類似於

DB::statement('SET FOREIGN_KEY_CHECKS=0;'); 
$table->integer('installateurtype_id')->unsigned(); 
$table->foreign('installateurtype_id')->references('id')->on('installateur_types')->onDelete('cascade'); 
DB::statement('SET FOREIGN_KEY_CHECKS=1;');