我不能删除唯一索引

I can't drop unique index

我创建了唯一索引:

 $table->unique(['owner_id', 'promoter_id']);

现在我托盘掉了

$table->dropUnique(['owner_id', 'promoter_id']);

General error: 1553 Cannot drop index 'connections_owner_id_promoter_id_unique': needed in a foreign key constraint (SQL: alter table connections drop index connections_owner_id_promoter_id_unique)

此外,我之前尝试删除外键

$table->dropForeign('connections_promoter_id_foreign');

但仍然没有结果

Laravel docs on Indexes 开始,您可以创建具有指定名称的唯一索引:

因此,为了避免调试 laravel 如何为索引构造名称,您可以在添加索引时为其分配一个名称,例如:

$table->unique(['owner_id', 'promoter_id'], 'owner_promoter_index');

然后drop的时候用同一个名字:

$table->dropUnique('owner_promoter_index');

基于这个 Drop muli-column unique key without dropping foreign key? 我得到了这个也有效的解决方案:

Schema::table('connections', function ($table){
            $table->index('owner_id');
            $table->dropUnique(['owner_id', 'promoter_id']);
        });

先取消约束。

对于 sqlserver: 如果不知道约束名,就用sp_helpconstraint TABLE_A,约束名可能和index一样。 然后 alter table TABLE_A drop constraint UQ__TABLE_A_XXXXXXXXXX。然后,删除索引。

在你的例子中

$table->unique(['owner_id', 'promoter_id']);

数组中的第一列已有外键和相关索引。

第一个选项将首先放置一个还没有外键的字段,例如

$table->unique(["key", 'owner_id', 'promoter_id']);

但这并不总是可能的

第二个选项 - 你只需要修改down()函数

例如,您可以像这样创建唯一索引

$table->unique(['owner_id', 'promoter_id']);

owner_id 是现在给您带来麻烦的字段,因为它在数组中排在第一位。因此,down 函数应该如下所示:

$table->dropForeign(['owner_id']);
$table->dropUnique(['owner_id', 'promoter_id']);
$table->foreign('owner_id')->references('id')->on('owners');

第三个选项有点棘手,你的'down'函数看起来像这样

$table->index('owner_id');
$table->dropUnique(['owner_id', 'promoter_id']);

它会起作用,但是我不推荐它,因为它不是一个“回滚”

如果以索引名称开头 records_owner_id_foreign 然后你做 php artisan migrate 然后 php artisan migrate:rollback 然后你会找到你的索引名称records_owner_id_index。它不再是相同的索引名称

所以你可以在不同的数据库中使用不同的索引名称,你喜欢吗?我没有。

试试这个方法:

   Schema::table('table_name', function (Blueprint $table) {
        
        
        //$table->dropIndex('language_title');            
        //$table->dropUnique('language_title');

        // Integrate them
        $table->dropIndex('language_title')->dropUnique('language_title');
    });