4.5 数据库迁移

生成

# 生成一份用于 创建 user_activity表的迁移文件
php bin/hyperf.php gen:migration user --create=user

# 生成一份用于 更新 user_activity表的迁移文件
php bin/hyperf.php gen:migration user --table=user

编写迁移文件

<?php

use Hyperf\Database\Schema\Schema;
use Hyperf\Database\Schema\Blueprint;
use Hyperf\Database\Migrations\Migration;

class User extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('user', function (Blueprint $table) {
            // 用户id
            $table->bigIncrements('id');
            // 名字
            $table->string('name', 255)->nullable(false)->default('')->comment('名字');
            // 年龄
            $table->tinyInteger('age', false, true)->nullable(false)->default(0)->comment('年龄');
            // 性别
            $table->string('sex', 50)->nullable(false)->default('未知')->comment('性别:未知、男、女');
            // 联系号码
            $table->string('mobile', 20)->nullable(false)->default('')->comment('联系号码');
            // 密码
            $table->char('password', 32)->nullable(false)->default('')->comment('密码');
            $table->timestamps();

            // 唯一索引:名字
            $table->unique('name', 'uqx_name');
            // 普通联合索引:联系号码
            $table->index(['name', 'mobile'], 'idx_name_mobile');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('user');
    }
}

运行

  • 在后面加 –force 则强制运行
php bin/hyperf.php migrate

回滚

  • 在后面加 –step=5 则只回滚最近的几次迁移
# 回滚最近的一次迁移文件
php bin/hyperf.php migrate:rollback

# 回滚最近5次的迁移文件
php bin/hyperf.php migrate:rollback --step=5

# 回滚全部的迁移文件
php bin/hyperf.php migrate:reset
文档更新时间: 2021-09-24 17:59   作者:赵豪