Joshua
Joshua

Reputation: 305

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?

Upvotes: 3

Views: 5896

Answers (1)

Marwelln
Marwelln

Reputation: 29413

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.

Upvotes: 16

Related Questions