2017-05-03 158 views
0

我一直在嘗試所有可能的解決方案,基於其他堆棧問題和答案,但我仍然沒有得到任何成功,所以我不得不提出自己的問題。一般錯誤:1215不能在表上添加外鍵約束

我有以下架構

Schema::create('file_data', function (Blueprint $table) { 
      $table->engine = 'InnoDB'; 
      $table->increments('id'); 

......

 Schema::create('claims', function (Blueprint $table) { 
      $table->engine = 'InnoDB'; 
     .... 
      $table->integer('file_id')->unsigned()->nullable()->default(DB::raw('NULL')); 

      .... 
      $table->foreign('budget_id') 
       ->references('id') 
       ->on('budgets') 
       ->onDelete('cascade'); 

     }); 

     Schema::create('claims_details', function (Blueprint $table) { 
      $table->engine = 'InnoDB'; 
      ......... 
      $table->integer('file_id')->unsigned()->nullable()->default(DB::raw('NULL')); 
      .......... 

     }); 

在另一個文件

Schema::table('claims', function(Blueprint $table){ 
     $table->foreign('file_id') 
      ->references('id') 
      ->on('file_data') 
      ->onDelete('cascade'); 
     }); 

     Schema::table('claims_details', function(Blueprint $table){ 
     $table->index(['invoice_date','claim_id']); 
     $table->foreign('claim_id') 
      ->references('id') 
      ->on('claims') 
      ->onDelete('cascade'); 
      $table->foreign('file_id') 
       ->references('id') 
       ->on('file_data'); 
     }); 

,當我運行命令php artisan migrate我碰到下面的錯誤

[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table claims add constraint claims_file_id_ foreign foreign key (file_id) references file_data (id) on delete cascade)

  • 表是Innob
  • 的列是同一類型的
  • 列是無符號
  • 文件以正確的順序
  • 唯一不同的運行是file_id的需要爲null (他們必須)

是因爲該列是「空」馬kes它失敗了?我嘗試了它,而不是它爲空,仍然失敗。什麼是導致它有這個問題的其他原因?

+0

在外鍵約束條件下'file_id'是可以爲空的。我想知道爲什麼你的外鍵引用'file_data.id'雖然,而不是'files.id'。難道在'files'和'file_data'之間存在1對0/1的關係嗎? –

+0

如果你可以在創建外鍵之前先刪除數據,我認爲它是可行的。第二種選擇是,您必須檢查外鍵字段值是否與主鍵表值存在。 –

+0

@reds第一個選項已經完成,因爲我正在設置。你能解釋第二種選擇嗎? – Kendall

回答

1

原來我需要列索引

+1

當然,InnoDB的特有之一! http://stackoverflow.com/questions/6230588/foreign-keys-must-be-index-in-mysql –