Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using migrations to delete table with foreign key

Im 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`)  

Im not exactly sure what to do to fix this.

Edit:

I have tried: $table->dropForeign('pm_convo_user_one_foreign');

But im getting errors with that as well

like image 625
BigJobbies Avatar asked Jun 14 '13 12:06

BigJobbies


People also ask

Can we delete a table with foreign key?

To delete a foreign key constraintIn Object Explorer, expand the table with the constraint and then expand Keys. Right-click the constraint and then click Delete. In the Delete Object dialog box, click OK.

What is foreign key in laravel migration?

Foreign Keys Laravel also provides support for adding foreign key constraints to your tables: $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users'); In this example, we are stating that the user_id column references the id column on the users table.


1 Answers

I think this is a better way to do it:

public function down() {     DB::statement('SET FOREIGN_KEY_CHECKS = 0');     Schema::dropIfExists('tableName');     DB::statement('SET FOREIGN_KEY_CHECKS = 1'); } 
like image 105
Eric Chan Avatar answered Sep 30 '22 19:09

Eric Chan