1

I have lots of migrations and usually use 'php artisan migrate:refresh' and everything is fine.

For the first time I get an error while rollbacking because of a duplicate entry for a unique column:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'record' for key 'objects_key_unique' (SQL: alter table `objects` add unique `objects_key_unique`(`key`))

At first the column was unique but in a later migration I removed that constraint and now I have duplicate entries in my database.
The migration throws an error when I rollback because of the down function where the unique constraint is set again.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class EditObjectTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('objects', function (Blueprint $table) {
            $table->dropUnique(['key']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('objects', function (Blueprint $table) {
            $table->unique(['key']);
        });
    }
}

How can I handle this? I do not want the column to have a unique constraint, but I also want to rollback without getting an error. Shortly after the "EditObjectTable" the table is dropped in another migration, so i do not need the data when I rollback.

N3R4ZZuRR0
  • 2,400
  • 4
  • 18
  • 32
tverdo
  • 122
  • 10
  • 1
    Also add `$table->dropUnique(['key']);` in `down` function – Zain Farooq Sep 10 '19 at 08:20
  • I thought the meaning behind migrations is that up and down functions do the exact opposite of another. In my case the table will be dropped and it probably would work, but in other cases there might be another migration between mine and the createTable one which assumes that the unique constraint is set. – tverdo Sep 10 '19 at 08:54
  • Your case is special and I think you need to remove unique constraint in down function – Zain Farooq Sep 10 '19 at 09:14

1 Answers1

0

I think you need to check down method of drop table migration file. I have tested your example.but it's working fine. if you added unique constrains into down method. then you have to remove unique constrains.

  • The migration before mine, the up function creates the table 'objects' with the unique constraint on 'key' and the down function drops the table. So a pretty common create migration file. – tverdo Sep 10 '19 at 09:17