2017-06-21 100 views
1

我有一個表已創建的外鍵約束:Laravel改變外鍵約束

$table->foreign('cms_id')->references('id')->on('inventories'); 

我需要,使其在inventories表引用remote_id而不是id列改變這種外鍵。

我試圖通過這樣做:

public function up() 
    { 
     Schema::table('contents', function (Blueprint $table) { 
      $table->dropForeign('contents_cms_id_foreign'); 
      $table->foreign('cms_id')->references('remote_id')->on('inventories'); 
     }); 
    } 

但是,我得到:

[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL : alter table contents add constraint contents_cms_id_foreign foreign k ey (cms_id) references inventories (remote_id))

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

+0

確保'cms_id'和'remote_id'具有相同的類型,大小和相同的屬性(如'UNSIGNED'等)。 – lesssugar

+0

它們屬於同一類型,並且具有相同的屬性,但我仍然得到相同的錯誤 – Leff

回答

0

兩個步驟添加新的外鍵,除了分離到Schema::table

public function up() 
{ 
    Schema::table('contents', function (Blueprint $table) { 
     $table->dropForeign('contents_cms_id_foreign'); 
     $table->integer('cmd_id')->unsigned(); 
    }); 

    Schema::table('contents', function (Blueprint $table) { 
     $table->foreign('cms_id')->references('remote_id')->on('inventories'); 
    }); 
} 
+0

我沒有db中的任何記錄 – Leff

+0

如果在那種情況下,您不需要'nullable()'方法 –

+0

但是,我仍然得到相同的錯誤 – Leff