Search code examples
laravellaravel-4

Using migrations to delete table with foreign key


I am trying to roll back my migrations.

My migrations file uses foreign keys like so:

$table->foreign('user_one')->references('id')->on('users');
$table->foreign('user_two')->references('id')->on('users');

My down() function is like so:

public function down()
{
    Schema::drop('pm_convo');
    Schema::drop('pm_convo_replys');
}

When I run my migrate command:

php artisan migrate:refresh --seed --env=local

I am getting the following error:

SQLSTATE[23000]: Integrity constraint violation: 1217 Cannot delete or update a parent row: a foreign key constraint fails (SQL: drop table `pm_convo`) 

I am not exactly sure what to do to fix this.

I have tried: $table->dropForeign('pm_convo_user_one_foreign');, but I am getting errors with that as well.


Solution

  • pm_convo_replys has a foreign key that references pm_convo, thus you cannot delete pm_convo first without violating a foreign key constraint in pm_convo_replys.

    To delete both you need to delete pm_convo_replys first.

    public function down()
    {
        Schema::drop('pm_convo_replys');
        Schema::drop('pm_convo');
    }