2014-10-29 78 views
3

我的外鍵涉及其自己的表。這是爲了生成帖子,其層級爲問題與丟棄外鍵

現在,當我嘗試在數據庫中刪除列,它給了我這個錯誤:

1553 - Cannot drop index 'post_field_properties_parent_id_index': needed in a foreign key constraint 

這是代碼:

public function down() 
{ 
     Schema::table("post_field_properties", function($table) 
     { 
      $table->dropForeign('parent_id'); 
      $table->dropColumn('parent_id'); 
     }); 
} 

我似乎能的唯一途徑做到這一點,是要轉到phpmyadmin並刪除外鍵本身。然後刪除列。

+0

哪些表名,你通過外鍵連接了嗎? – 2014-10-29 10:44:43

+1

「parent_id」是否真的是外鍵的名字?通常情況下,就像[這裏]顯示的一樣(http://laravel.com/docs/4.2/schema#foreign-keys) – lukasgeiter 2014-10-29 10:49:04

回答

1

嘗試將「_foreign」放在列名的末尾。例如:

public function down() 
{ 
     Schema::table("post_field_properties", function($table) 
     { 
      $table->dropForeign('parent_id_foreign'); 
      $table->dropColumn('parent_id'); 
     }); 
} 
+0

謝謝我會試試這個 – Jimmyt1988 2014-10-29 11:28:59

9

剛剛爲我自己的項目弄明白了這一點。當你刪除一個外鍵,你需要連接的表名和約束中的列然後用後綴名「_foreign」

http://laravel.com/docs/5.1/migrations#foreign-key-constraints

public function down() 
{ 
     Schema::table("post_field_properties", function($table) 
     { 
      $table->dropForeign('post_field_properties_parent_id_foreign'); 
      $table->dropColumn('parent_id'); 
     }); 
} 
+1

Works也在5.2 :)非常有幫助謝謝! – 2016-02-21 06:35:37

+1

在5.3中工作!謝謝。 – Notflip 2017-02-07 08:11:50

+0

(可選)您可以通過將數組傳遞給dropForeign方法來指定要刪除的外鍵的列名: '$ table-> dropForeign(['parent_id']);' 刪除外鍵非常重要在刪除相關列之前關鍵。 – 2017-05-24 10:35:22

0

要檢查外鍵的名稱,第一次備份您的數據庫.SQL

在那裏你會看到你的外鍵的名稱是這樣的:

... 
KEY `employees_parent_id_foreign` (`parent_id`), 
CONSTRAINT `employees_parent_id_foreign` FOREIGN KEY (`parent_id`) REFERENCES `laravel_article` (`id`) ON DELETE CASCADE 
... 
在我的CAS

e是laravel 5.4, 它通過這種格式開始:tablename_columnname_foreign

所以在您的laravel(在這裏,我嘗試刪除從員工表的外鍵)

Schema::table("employees", function($table) 
{ 
    $table->dropForeign('employees_parent_id_foreign'); 
    $table->dropColumn('parent_id'); 
});