繁体   English   中英

无法删除索引“***”:外键约束中需要

[英]Cannot drop index '***': needed in a foreign key constraint

我创建了唯一索引:

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

现在我托盘放下它

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

一般错误:1553 无法删除索引“connections_owner_id_promoter_id_unique”:在外键约束中需要(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');

然后,当您删除它时,您使用相同的名称:

$table->dropUnique('owner_promoter_index');

基于这个Drop 多列唯一键而不丢弃外键? 我得到了这个也有效的解决方案:

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

在你的例子中

$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');

第三个选项有点棘手,你的“向下”功能看起来像这样

$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');
    });

从错误消息来看,您似乎在同一运行中创建了一个外键和唯一的 touple,如下所示:

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

来自mysql 文档

MySQL 要求对外键列进行索引; 如果创建具有外键约束但在给定列上没有索引的表,则会创建索引。

现在,当您创建了一个元组索引时, owner_id已经有了一个索引,并且 MySQL 不需要创建一个 foreign_key 索引。 但是,如果您现在删除唯一键约束,您将拥有一个没有索引的外键。 这是不允许的,因此您的错误消息。

无需删除外键。 在删除唯一索引之前,只需在字段上添加一个普通索引。 像这样:

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

而已。 外键错误不会出现,因为您已将其编入索引。

无需禁用或删除唯一索引! 只需用另一个索引覆盖 UNIQUE 索引!

Schema::table('users', function (Blueprint $table) {
    $table->unique(['user_id', 'role_id', 'department_id'],
       'user_roles_user_id_role_id_department_id_unique');
});

使用PHP管理员,我有同样的问题,但很容易从那里做到!

首先删除约束。

对于 sqlserver:如果不知道约束名,使用sp_helpconstraint TABLE_A ,约束名可能与索引相同。 然后alter table TABLE_A drop constraint UQ__TABLE_A_XXXXXXXXXX 。然后,删除索引。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM