ThinkPHP5.1中数据库迁移migration与数据填充Faker的使用

数据库迁移工具 think-migration

通过composer安装

1
composer require topthink/think-migration=2.0.*

安装完成后,在命令行下查看,就会发现新增了几个migrateseed命令

1
php think
1
migrate
2
 migrate:create     Create a new migration
3
 migrate:rollback   Rollback the last or to a specific migration
4
 migrate:run        Migrate the database
5
 migrate:status     Show migration status
6
optimize
7
 optimize:autoload  Optimizes PSR0 and PSR4 packages to be loaded with classmaps too, good for production.
8
 optimize:config    Build config and common file cache.
9
 optimize:route     Build route cache.
10
 optimize:schema    Build database schema cache.
11
seed
12
 seed:create        Create a new database seeder
13
 seed:run           Run database seeders

创建迁移类

1
php think migrate:create Users

可以看到在根目录下创建了迁移文件 .\database\migrations\20200420115806_users.php

change()方法中,编写创建表结构的代码。可以在up()方法中进行修改数据库,down()方法中进行回滚操作。
更详细的使用方法参考中文文档

1
<?php
2
3
use think\migration\Migrator;
4
use think\migration\db\Column;
5
6
class Users extends Migrator
7
{
8
    public function change()
9
    {
10
        $table = $this->table('users',array('engine'=>'InnoDB'));
11
        $table->addColumn('username', 'string',array('limit' => 15,'default'=>'','comment'=>'用户名,登陆使用'))
12
            ->addColumn('password', 'string',array('limit' => 32,'default'=>md5('123456'),'comment'=>'用户密码'))
13
            ->addColumn('is_delete', 'boolean',array('limit' => 1,'default'=>0,'comment'=>'删除状态,1已删除'))
14
            ->addIndex(array('username'), array('unique' => true))
15
            ->create();
16
    }
17
18
    public function up()
19
    {
20
21
    }
22
23
    public function down()
24
    {
25
26
    }
27
}

执行迁移

1
php think migrate:run

执行迁移命令后创建如下两张表:

  • migrations 这个表就是用来管理数据库的表
  • users 就是我们创建的用户表

avatar

数据填充 Faker

安装 Faker

Faker GitHub

1
composer require fzaninotto/faker

创建数据生成文件

1
php think seed:create UserSeeder

创建了新文件 .\database\seeds\UserSeeder.php

1
<?php
2
3
use think\migration\Seeder;
4
5
class UserSeeder extends Seeder
6
{
7
    public function run()
8
    {
9
        $faker = Faker\Factory::create('zh_CN');
10
11
        $data = [];
12
        // 循环生成50条数据
13
        for ($i = 0; $i < 50; $i++) {
14
            $data[] = [
15
                'username'      => $faker->name,
16
                'password'      => md5($faker->password),
17
            ];
18
        }
19
        $this->insert('users', $data);
20
    }
21
}

运行命令生成数据

1
php think seed:run

此时再去数据库查看,就生成了50条数据


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!