thinkphp6.0 数据库迁移migration与数据填充Faker的使用

之前在学习laravel框架的时候觉得数据迁移和数据填充很好用,所以最近在学习tp6的时候,也想用一下,但是框架里写的比较简单,通过查找相关资料整理一下用法。

数据库迁移工具

首先通过 composer 安装

composer require topthink/think-migration=2.0.*

安装好之后再控制台输入命令

php think

创建迁移类文件,首字母必须大写

php think migrate:create UserAccount

可以看到目录下有.\database\migrations\20200218062948_user_account.php

使用实例

<?php

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

class UserAccount 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()
    {
        $table  =  $this->table('users',array('engine'=>'MyISAM'));
        $table->addColumn('username', 'string',array('limit'  =>  15,'default'=>'','comment'=>'用户名,登陆使用'))
        ->addColumn('password', 'string',array('limit'  =>  32,'default'=>md5('123456'),'comment'=>'用户密码')) 
        ->addColumn('login_status', 'boolean',array('limit'  =>  1,'default'=>0,'comment'=>'登陆状态'))
        ->addColumn('login_code', 'string',array('limit'  =>  32,'default'=>0,'comment'=>'排他性登陆标识'))
        ->addColumn('last_login_ip', 'integer',array('limit'  =>  11,'default'=>0,'comment'=>'最后登录IP'))
        ->addColumn('last_login_time', 'datetime',array('default'=>0,'comment'=>'最后登录时间'))
        ->addColumn('is_delete', 'boolean',array('limit'  =>  1,'default'=>0,'comment'=>'删除状态,1已删除'))
        ->addIndex(array('username'), array('unique'  =>  true))
        ->create();
    }
}

这里可以参考phinx 的文档来使用
phinx官方文档
phinx中文文档

change方法编写完成后在控制台输入以下命令,即可自动创建数据表

php think migrate:run

查看自动创建的表

如果数据表创建的有误或者需要新增、修改、删除字段,可以使用php think migrate:rollback命令回滚,修改完之后再次执行 php think migrate:run 即可

数据填充

首先通过命令行安装Faker

composer require fzaninotto/faker

生成一个seed文件

php think seed:create Users

可以看到有一个新的文件.\database\seeds\Users.php

编写假数据的生成逻辑

public function run()
    {
        // faker默认语言是英文会生成英文的数据,在创建实例的时候可以指定为中文
        $faker = Faker\Factory::create('zh_CN');
        $rows = [];
        for ($i = 0; $i < 50; $i++) {
            $rows[] = [
                'username'      => $faker->name,
                'password'      => md5($faker->password),
                 'phone'         => $faker->phoneNumber,
            ];
        }

        Db::table('users')->insertAll($rows);
    }

在命令行输入一下命令并执行

php think seed:run

出现下图红色的部分说明成功了

可以查看一下数据库

发布了36 篇原创文章 · 获赞 8 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_41965172/article/details/104379192