2017-09-25 36 views
2

我試圖創建數據透視表,外鍵,這是我在Laravel做出遷移:不能外鍵約束添加到數據透視表

public function up() 
{ 
    Schema::create('player_position', function (Blueprint $table) { 
     $table->integer('player_id')->unsigned()->index(); 
     $table->integer('position_id')->unsigned()->index(); 

     $table->foreign('player_id')->references('id')->on('players')->onDelete('cascade'); 
     $table->foreign('position_id')->references('id')->on('positions')->onDelete('cascade'); 
    }); 
} 

但是,我得到一個錯誤:

[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table player_position add constraint player_position_posi tion_id_foreign foreign key (position_id) references positions (id) on delete cascade)

                  [PDOException]               

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

我已閱讀,通常外鍵約束的錯誤是沒有左右分配給無符號的字段,或者已經有在DB的記錄,但我的數據庫是空的,我在我的領域都簽名,所以不知道問題是什麼?

+0

我建議你不要在你的db上使用約束。相反,嘗試在你的代碼中進行管理。 –

+0

@MortezaRajabi和它爲什麼如此? –

+0

用約束來管理這樣一個表很困難,每次你想添加或刪除一些東西時你都會遇到這些錯誤。 –

回答

0

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

對於一個字段被定義爲foreign key,引用的父字段必須有一個index上定義。並且列和其大小的數據類型必須相同。

我認爲你違反了上述規定。

+0

但是,他們確實有索引定義 – Leff

+0

那'datatype'呢? –

+0

以及它們都是整數 – Leff

0

刪除- > index()方法,因爲它創建基本索引,而您想添加引用主鍵在另一個表上的外鍵約束。

$table->integer('player_id')->unsigned(); 
$table->integer('position_id')->unsigned(); 

$table->foreign('player_id')->references('id')->on('players')->onDelete('cascade'); 
$table->foreign('position_id')->references('id')->on('positions')->onDelete('cascade');