laravel 中的回滚迁移

问题描述 投票:0回答:1

我想在迁移中写下()函数,运行回滚命令后出现错误。

我想要回滚的迁移看起来像这样:

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']);
        });
    }

回滚函数如下所示:

public function down(): void
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->dropColumn('competition_id');
        });
    }

当我运行 php artisan migrate:rollback 时,出现此错误:

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`)

我做错了什么?

php laravel migration rollback
1个回答
0
投票

发生错误的原因是您尝试删除唯一约束的列部分。在删除列之前,必须先删除唯一约束。

public function down(): void
{
    Schema::table('posts', function (Blueprint $table) {
        $table->dropUnique(['account_id', 'competition_id']); // Drop the unique constraint first
        $table->dropForeign(['competition_id']); // Then drop the foreign key constraint
        $table->dropColumn('competition_id'); // Finally, drop the column
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.