Laravel 4 不能删除外键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23319801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:25:43  来源:igfitidea点击:

Laravel 4 cannot drop foreign key

phplaravel

提问by Joshua

I am trying to drop Foreign key on a table, but I got this message:

我正在尝试将外键放在表上,但收到以下消息:

[Illuminate\Database\QueryException]                                         
  SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'user_id  
  '; check that column/key exists (SQL: alter table `posts` drop foreign key   
  user_id)   

And I am using migration to do this:

我正在使用迁移来做到这一点:

Schema::table('posts', function($table) {
            $table->dropForeign('user_id');
            $table->foreign('user_id')
                  ->references('id')->on('users')
                  ->onDelete('cascade');
        }); 

I am sure that the 'user_id' exists in the 'posts' table:

我确定 'user_id' 存在于 'posts' 表中:

 Field      | Type             | Null | Key | Default             | Extra          |
+------------+------------------+------+-----+---------------------+----------------+
| id         | int(10) unsigned | NO   | PRI | NULL                | auto_increment |
| user_id    | int(10) unsigned | NO   | MUL | NULL                |                |

How can I fix this? Is it a bug or something?

我怎样才能解决这个问题?是bug还是什么?

------------------
update:
I found that the reason might be that "you are trying to delete a key which is being used by another table."
Does that means I should drop those tables that uses 'posts' table first?

------------------
更新:
我发现原因可能是“您正在尝试删除另一个表正在使用的键”。
这是否意味着我应该先删除那些使用“posts”表的表?

回答by Marwelln

When creating a foreign key, the name will be table_fields_foreignunless you set a name in the second parameter (see createIndexNamemethod).

创建外键时,table_fields_foreign除非您在第二个参数中设置名称(请参阅createIndexName方法),否则名称将为。

So if you didn't specify a name your foreign key should be posts_user_id_foreignand not user_id.

因此,如果您没有指定名称,您的外键应该是posts_user_id_foreign而不是user_id.