How to drop an unique key from foreign key constraint?
I have a 1:1 relation, called user_Xs which has a user_id column, that points to users table. I want to add a unique key to user_id, so that there's never going to be a duplicated row in a one to one relation, so what I did in a different migration:
$table->unique('user_id');
But I don't know how to remove that unique key without removing the whole index in down() or in case for example in future I want to turn the one to one relation into one to many.
currently I wrote:
$table->dropUnique(['user_id']);
but it tries to remove the whole index which mysql says: Cannot drop index 'user_Xs_user_id_unique': needed in a foreign key constraint
When you create a unique index its always for all the records in the table. You can't do it for a specific record, at least not in a way that it would be useful.
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('user_Xs', function (Blueprint $table) {
DB::statement('ALTER TABLE `user_Xs` DROP INDEX `user_Xs_user_id_foreign`, ADD UNIQUE `user_Xs_user_id_unique` (`user_id`) USING BTREE; ');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('user_Xs', function (Blueprint $table) {
DB::statement('ALTER TABLE `user_Xs` DROP INDEX `user_Xs_user_id_unique`, ADD INDEX `user_Xs_user_id_foreign` (`user_id`) USING BTREE;');
});
}
};