I want to write down() function in migration and after run rollback command I’m getting error.
Migration that i want to rollback looks like this:
public function up(): void
{
Schema::table('posts', function (Blueprint $table) {
$table->foreignId('competition_id')->after('content_id')->nullable()->constrained('competitions');
$table->unique(['account_id', 'competition_id']);
});
}
Rollback function looks like this:
public function down(): void
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('competition_id');
});
}
When I run php artisan migrate:rollback I’m getting this error:
SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'competition_id' doesn't exist in table (Connection: mysql, SQL: alter table `posts` drop `competition_id`)
What I’m doing wrong?
2
Answers
Finally I figured it out. I must rollback in the following order.
Drop both foreign keys that are part of composite unique constraint:
Drop composite unique constraint:
Drop column:
Finally recreate account_id foreign key:
So the final migration looks like this:
You need to drop the foreign key constraint before you can drop the unique index.