samedi 25 juillet 2020

I need to update existing foreign key, but I can't drop it in order to update it

I've got a migration to correct existing foreign key, it looks like this

public function up()
{
    Schema::table('content_term', function (Blueprint $table) {
        $table->dropForeign('content_term_content_id_foreign');
        $table->foreign('content_id')->references('id')->on('content')->onUpdate('cascade')->onDelete('cascade');
    });
}

The original table and foregin key looked like this

public function up()
{
    Schema::create('content_term', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedBigInteger('content_id')->unsigned();
        $table->unsignedInteger('term_id');

        $table->foreign('content_id')->references('id')->on('content')->onUpdate('cascade');
        $table->foreign('term_id')->references('id')->on('terms')->onDelete('cascade')->onUpdate('cascade');
    });
}

I forgot to add onDelete('cascade') for content_id foreign key creation and need to correct that in a new migration.

When I run php artisan migrate with thew latest migration I've added I get this

enter image description here

SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'content_term_content_id_foreign'; check that column/key exists (SQL: alter table content_term drop foreign key content_term_content_id_foreign)

MYSQL complains that the foreign key does not exist in content_term table. When I check that table using phpmyadmin I can clearly see that key exists. See attached pic for proof of that.

enter image description here

What's the problem with my new migration, why is this line causing a problem:

$table->dropForeign('content_term_content_id_foreign');


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire