【问题标题】:Laravel changing foreign key constraintLaravel 改变外键约束
【发布时间】:2017-11-24 02:06:25
【问题描述】:

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

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

我需要更改此外键,使其引用remote_id 而不是inventories 表中的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');
        });
    }

但是,我明白了:

[照亮\数据库\查询异常]
SQLSTATE[HY000]:一般错误:1215 无法添加外键约束 (SQL : alter table contents 添加约束 contents_cms_id_foreign 外键 (cms_id) 引用 inventories (remote_id))

[PDO异常]
SQLSTATE[HY000]: 一般错误:1215 无法添加外键约束

【问题讨论】:

  • 确保cms_idremote_id 的类型、大小和属性相同(例如UNSIGNED 等)。
  • 它们属于同一类型,具有相同的属性,但我仍然得到相同的错误

标签: php mysql laravel foreign-keys


【解决方案1】:

除了分隔到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');
    });
}

【讨论】:

  • 我的数据库中没有任何记录
  • 如果在那种情况下,你不需要nullable()方法
猜你喜欢
  • 2018-12-07
  • 2015-05-21
  • 2016-08-17
  • 2020-04-21
  • 2019-03-27
  • 1970-01-01
  • 2020-09-12
  • 2015-09-22
  • 2020-07-22
相关资源
最近更新 更多