Files
vibe_coding/.cursor/skills/database-migration/references/rollback-patterns.md
2026-03-05 21:27:11 +08:00

1.3 KiB

数据库回滚模式 (Hyperf Migration)

安全回滚策略

添加字段(可回滚)

// Migration up()
Schema::table('users', function (Blueprint $table) {
    $table->string('avatar_url')->nullable()->after('email');
});

// Migration down()
Schema::table('users', function (Blueprint $table) {
    $table->dropColumn('avatar_url');
});

删除字段(不可逆 — 需预备份)

-- 删除前先备份
CREATE TABLE _backup_users_phone AS
SELECT id, phone FROM users WHERE phone IS NOT NULL;

重命名字段(分步迁移)

// Step 1: 添加新列
Schema::table('users', function (Blueprint $table) {
    $table->string('display_name')->nullable()->after('name');
});

// Step 2: 迁移数据
DB::statement('UPDATE users SET display_name = name');

// Step 3: 删除旧列(下一个迁移文件)
Schema::table('users', function (Blueprint $table) {
    $table->dropColumn('name');
});

类型变更(分步迁移)

Step 1: 添加新列 → Step 2: 迁移数据 → Step 3: 删除旧列

回滚命令

# 回滚最近一次迁移
php bin/hyperf.php migrate:rollback

# 回滚最近 N 次迁移
php bin/hyperf.php migrate:rollback --step=3

# 查看迁移状态
php bin/hyperf.php migrate:status