【问题标题】:Laravel 5.4 - Error dropping unique constraint on foreign key [duplicate]Laravel 5.4 - 删除外键的唯一约束时出错[重复]
【发布时间】:2018-12-02 05:49:39
【问题描述】:

我正在尝试删除唯一约束,但一直遇到外键约束问题:

这是原始迁移:

Schema::table('table', function (Blueprint $table) {
    $table->bigInteger('other_table_id')->unsigned()->unique()->nullable();
    $table->foreign('other_table_id')->references('id')->on('other_table')->onDelete('set null');
});

快进到现在,我正在尝试从表上的列中删除 UNIQUE 约束而不影响外键

Schema::table('table', function (Blueprint $table) {
    $table->dropUnique('table_other_table_id_unique');
});

这是我遇到的错误。

SQLSTATE[HY000]: General error: 1553 Cannot drop index 'table_other_table_id_unique': needed in a foreign key constraint

我也试过

Schema::table('table', function (Blueprint $table) {
    $table->dropUnique(['other_table_id']);
});

但这也没有用。

我什至尝试在迁移时禁用外键约束:

Schema::disableForeignKeyConstraints(); // Disable constraint

Schema::table('table', function (Blueprint $table) {
    $table->dropUnique(['other_table_id']);
});

Schema::enableForeignKeyConstraints(); // Reenable constraint

似乎没有任何效果。我究竟做错了什么?

【问题讨论】:

  • @JoelHinz 谢谢你的链接。它给了我足够的信息来回答我自己的问题。我已经在下面回答了我的解决方案。但是,我会将您的链接标记为答案。

标签: laravel foreign-keys unique-constraint laravel-migrations


【解决方案1】:

link Joel Hinz 的评论足以回答我的问题。我正在回答我自己的问题,因为我可以使用特定于 Laravel 的代码来提供答案。

问题源于外键使用唯一键作为其键。因此,必须先删除外键,然后再删除唯一键,然后重新设置外键。

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('table', function (Blueprint $table) {
        $table->dropForeign(['other_table_id']);
        $table->dropUnique(['other_table_id']);

        $table->foreign('other_table_id')->references('id')->on('other_table')->onDelete('set null');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('table', function (Blueprint $table) {
        $table->unique('other_table_id');
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-23
    • 2011-03-30
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    相关资源
    最近更新 更多