Laravel更改外键约束

时间:2017-06-21 09:04:18

标签: php mysql laravel foreign-keys

我有一个已经创建了外键约束的表:

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

我需要更改此外键,以便它引用remote_id表中的id而非inventories列。

我试过这样做:

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

但是,我明白了:

  

[照亮\数据库\ QueryException]
  SQLSTATE [HY000]:常规错误:1215无法添加外键约束   (SQL:alter table contents添加约束   contents_cms_id_foreign外国人(cms_id)引用   inventoriesremote_id))

     

[PDOException]
  SQLSTATE [HY000]:常规错误:1215无法添加外键约束

1 个答案:

答案 0 :(得分:2)

分两步添加新外键,除了分隔为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');
    });
}