2017-06-21 145 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