0

I'm trying to drop a unique constraint and I keep running into a foreign key constraint issue:

Here's the original migration:

Schema::table('table', function (Blueprint $table) {
    $table->bigInteger('other_table_id')->unsigned()->unique()->nullable();
    $table->foreign('other_table_id')->references('id')->on('other_table')->onDelete('set null');
});

Fast forward to now, I'm trying to drop the UNIQUE constraint from the column on the table without affecting the foreign key.

Schema::table('table', function (Blueprint $table) {
    $table->dropUnique('table_other_table_id_unique');
});

Here's the error I'm getting.

SQLSTATE[HY000]: General error: 1553 Cannot drop index 'table_other_table_id_unique': needed in a foreign key constraint

I've also tried using

Schema::table('table', function (Blueprint $table) {
    $table->dropUnique(['other_table_id']);
});

But that didn't work either.

I even tried disabling the foreign key constraint while doing the migration:

Schema::disableForeignKeyConstraints(); // Disable constraint

Schema::table('table', function (Blueprint $table) {
    $table->dropUnique(['other_table_id']);
});

Schema::enableForeignKeyConstraints(); // Reenable constraint

Nothing seems to work. What am I doing wrong?

Oscar A Garcia
  • 173
  • 5
  • 18
  • @JoelHinz thank you for the link. It gave me enough information to answer my own question. I've answered with my solution below. However, I'll mark your link as the answer. – Oscar A Garcia Jun 22 '18 at 18:24

1 Answers1

1

The link Joel Hinz had commented was enough information to answer my question. I'm answering my own question since I can provide the answer with code specific to Laravel.

The issue stemmed from the foreign key using the unique key as its key. Therefore, the foreign key must be dropped before dropping the unique key, then set up the foreign key again.

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('table', function (Blueprint $table) {
        $table->dropForeign(['other_table_id']);
        $table->dropUnique(['other_table_id']);

        $table->foreign('other_table_id')->references('id')->on('other_table')->onDelete('set null');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('table', function (Blueprint $table) {
        $table->unique('other_table_id');
    });
}
Oscar A Garcia
  • 173
  • 5
  • 18