Ad

Laravel6: How To Change References Of A Foreign Key With Migration

- 1 answer

I have tried to change foreign key reference by dropforeign key.I think everything is ok but i get this error:

SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP FOREIGN KEY teacher_schedule_calendars_product_id_foreign; check that it exists (SQL: alter table teacher_schedule_calendars drop foreign key teacher_schedule_calendars_product_id_foreign)

How can I solve it?

my migration code is :

Schema::table('teacher_schedule_calendars', function (Blueprint $table) {
    $table->dropForeign(['product_id']);
    $table->foreign('product_id')->references('id') ->on('courses')->onDelete('cascade');  
});

firstly, I ave removed the foreign and then add references. but it did not work.

Ad

Answer

I'm assuming you created a foreign key on the product_id column in a previous migration and you simply want to renew it or replace it with a foreign key to another table. In this case, what you are attempting to do might be problematic due to the way how migrations work and how individual database grammatics translate the commands.

What you can do to mitigate the issue is splitting the commands into two Schema::table($table) blocks:

Schema::table('teacher_schedule_calendars', function (Blueprint $table) {
    $table->dropForeign(['product_id']));
});

Schema::table('teacher_schedule_calendars', function (Blueprint $table) {
    $table->foreign('product_id')->references('id')->on('courses')->onDelete('cascade');  
});
Ad
source: stackoverflow.com
Ad