Laravel 5.4-错误删除外键上的唯一约束

时间:2018-06-22 17:45:46

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

我正在尝试删除唯一约束,并且不断遇到外键约束问题:

这是原始迁移:

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

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

1 个答案:

答案 0 :(得分:0)

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');
    });
}
相关问题