tp6数据填充

Author Avatar
yyq 2021-07-15 10:52:58
  • 二维码

tp6数据填充扩展安装与使用

        在开发项目时数据表经常需要使用些测试数据,在TP6中提供了相关的扩展,测试使用方式记录下。


        NO1:安装数据填充扩展,执行命令:php require fzaninotto/faker

    

        NO2:安装完成后使用上篇介绍的相关命令生成数据表,执行命令 php think migrate:create UsersTest 将会生成迁移文件xxx_users_test.php,修改change方法示例如下:

                public function change()

                {

                    $table  =  $this->table('userstest');

                    $table->addColumn('username', 'string',array('limit'  =>  15,'default'=>'','comment'=>'用户名,登陆使用'))

                          ->addColumn('password', 'string', array('limit'  =>  32, 'default'=>'','comment'=>'用户密码'))

                          ->addColumn('phone', 'string', array('limit'  =>  16, 'default'=>'','comment'=>'用户号码'))

                          ->create();

                }

            


        NO3:执行命令 php think migrate:run 将会生成userstest数据表及指定的字段


        NO4:userstest表已经有了,执行命令 php think seed:create UsersTest,将会在database目录下生成seeds/UsersTest.php文件,里面只有一个run方法,修改方法示例如下:(注意使用到了Db类,需要在头部引入 think/facade/Db; 其次row内的字段名跟表内字段要一致

                    public function run()

                    {

                            $faker = Faker\Factory::create('zh_CN');    // faker默认语言是英文会生成英文的数据,在创建实例的时候可以指定为中文

                            $rows = [];

                            for ($i = 0; $i < 50; $i++) {

                                $rows[] = [

                                    'username'      => $faker->name,

                                    'password'      => md5($faker->password),

                                    'phone'         => $faker->phoneNumber,

                                ];

                            }

                            Db::name('userstest')->insertAll($rows);

                    }

     

        NO5:最后执行生成测试数据命令  php think seed:run                  

上一篇 返回列表 下一篇

发表评论

Tips:评论内容请文明用语