使用think-migration进行数据库迁移

19 篇文章 1 订阅

前言:在thinkphp5中提供了数据迁移工具 (think-migration),开发者可以使用版本控制管理他们的数据库迁移。

文档:官方文档

安装方法:

首先通过 composer 安装:

composer require topthink/think-migration

注意事项,不支持修改文件配置目录。
在命令行下运行查看帮助,可以看到新增的命令。

php think 
 migrate
  migrate:breakpoint  Manage breakpoints
  migrate:create      Create a new migration
  migrate:rollback    Rollback the last or to a specific migration
  migrate:run         Migrate the database
  migrate:status      Show migration status
 seed
  seed:create         Create a new database seeder
  seed:run            Run database seeders

Create 命令

生成迁移文件模板:

//首字母必须为大写,会生成一个当前时间加xxx名称的迁移版本文件模板。
php think migrate:create UserList

在这里插入图片描述
在这里插入图片描述
在模板中的 change 方法中写入创建表的表名和字段。

<?php

use think\migration\Migrator;
use think\migration\db\Column;

class UserList extends Migrator
{
    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
     *
     * The following commands can be used in this method and Phinx will
     * automatically reverse them when rolling back:
     *
     *    createTable
     *    renameTable
     *    addColumn
     *    renameColumn
     *    addIndex
     *    addForeignKey
     *
     * Remember to call "create()" or "update()" and NOT "save()" when working
     * with the Table class.
     */
    public function change()
    {
        $this ->table('user_list', ['engine' => 'INNODB', 'collation' => 'utf8mb4_unicode_ci', 'id' => 'key', 'comment' => '用户列表'])
            ->addColumn('name', 'string', ['null' => true, 'limit' => 30, 'default' => '', 'comment' => '登录用户名'])
            ->addColumn('user_name', 'string', ['null' => true, 'limit' => 50, 'default' => '', 'comment' => '用户名'])
            ->addColumn('sex', 'integer', ['null' => true, 'limit' => 2, 'default' => 0, 'comment' => '性别,0女,1男'])
            ->addColumn('age', 'integer', ['null' => true, 'limit' => 10, 'default' => 0, 'comment' => '年龄'])
            ->addIndex(['user_name'])//添加索引
            ->create();
    }
}

Run 命令

执行迁移脚本:

//执行被 rollback 的迁移版本和新增加的迁移文件
php think migrate:run
//版本 id 单独执行某个版本 ( tp5.0 中试了不生效,在 phinx 有这个命令参数)
php think migrate:run -t 

注意:run 命令默认执行脚本的 up 方法,如果有 change 方法则执行 change 方法忽略 up,当在 change 方法中创建或者更新表的时候你必须使用 create()或者 update() 方法。

运行 php think migrate:run 以后就会在数据库中生成一张 user_list 表。

CREATE TABLE `user_list` (
  `key` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) COLLATE utf8mb4_unicode_ci DEFAULT '' COMMENT '登录用户名',
  `user_name` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT '' COMMENT '用户名',
  `sex` int(2) DEFAULT '0' COMMENT '性别,0女,1男',
  `age` int(10) DEFAULT '0' COMMENT '年龄',
  PRIMARY KEY (`key`),
  KEY `user_name` (`user_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户列表';

status 命令:
查看迁移日志和 git log 类似。

//查看迁移版本的执行列表,里面有记录执行状态,已执行(up方法)还是回滚(down方法),和每个版本的 id。
php think migrate:status

rollback 命令

回滚操作和git reset类似:

php think migrate:rollback	//回滚最后一次的版本
php think migrate:rollback -t	//版本 id 回滚到这个版本 id 的时间线,和 git 回滚操作相似(不包含这个版本 id )
php think migrate:rollback -t 0	//回滚所有的版本
php think migrate:rollback -t 0 -f	//如果断点阻塞了回滚,强制回滚到最初

rollback 命令默认执行脚本的 down 方法,如果有 change 方法则忽略 up ,自动回滚 change 方法的执行操作(有些操作无法支持回滚,会报异常)。

Breakpoint 命令

用来设置断点,可以使你对回滚进行限制,只能回滚到断点之后的版本。

php think migrate:breakpoint	//将断点设在最新的迁移版本上
php think migrate:breakpoint -t	//版本id 将断点打到版本id的迁移版本上
php think migrate:breakpoint -r	//移除所有断点

Seed 命令

Create 命令:
生成seed文件模板,seed:数据库填充工具。

//首字母必须为大写,会生成xxx名称的 seed 文件模板。
php think seed:create UserList

在这里插入图片描述
在这里插入图片描述
在模板 run 方法中写入需要添加的数据。

<?php
use Faker\Factory;
use think\Db;
use think\migration\Seeder;

class UserList extends Seeder
{
    /**
     * Run Method.
     *
     * Write your database seeder using this method.
     *
     * More information on writing seeders is available here:
     * http://docs.phinx.org/en/latest/seeding.html
     */
    public function run()
    {
        $faker = Factory::create('zh_CN');//选择中文
        $insert_data = [];
        for ($i=0;$i<11;$i++) {
            $insert_data[] = [
                'name'=>$faker->name,//随机姓名
                'user_name'=>$faker->name,//随机姓名
                'sex'=>$faker->numberBetween(0,1),//随机数字
                'age'=>$faker->numberBetween(20,30)//随机数字
            ];
            }
        Db::name('user_list')->insertAll($insert_data);
        return json(['code'=>1,'msg'=>'成功']);
    }
}

Run 命令

执行seed脚本:

php think seed:run //执行所有的 seed 文件
php think seed:run -s //文件名(不带 .php 后缀) 单独执行某个 seed 文件

运行完成,数据表中就会有数据了。
在这里插入图片描述

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Laravel 使用 Migration 来创建和管理数据库表,使得数据库的管理变得更加简单和高效。 以下是使用 Migration 在 Laravel 中创建数据库表的步骤: 1. 首先,在命令行中使用 `php artisan make:migration` 命令创建一个 Migration 文件,命令格式如下: ``` php artisan make:migration create_table_name --create=table_name ``` 其中,`create_table_name` 是 Migration 文件名,`table_name` 是要创建的数据库表名。 2. 接着,打开刚刚创建的 Migration 文件,可以看到该文件包含了两个函数:`up()` 和 `down()`。 `up()` 函数用于定义创建数据库表的操作,`down()` 函数用于定义回滚操作。 3. 在 `up()` 函数中,使用 Laravel 提供的 Schema 构建器来定义数据库表的结构,例如: ``` public function up() { Schema::create('users', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->timestamps(); }); } ``` 上述代码创建了一个名为 `users` 的数据库表,包含 `id`、`name`、`email`、`password` 和 `timestamps` 等字段。 4. 最后,在命令行中使用 `php artisan migrate` 命令将 Migration 文件中定义的数据库表结构应用到数据库中,命令格式如下: ``` php artisan migrate ``` 执行成功后,可以在数据库中看到新创建的 `users` 数据库表。 以上就是使用 Migration 在 Laravel 中创建数据库表的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值