简体   繁体   中英

Laravel 4 cannot drop foreign key

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:

 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?

------------------
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?

When creating a foreign key, the name will be table_fields_foreign unless you set a name in the second parameter ( see createIndexName method) .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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