簡體   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