tp8 数据迁移migrate和seed插入测试数据的完整示例

  • 原创
  • 作者:程序员三丰
  • 发布时间:2024-03-27 23:47
  • 浏览量:934
本文通过一个简单的实例实践,来分享如何在tp8使用数据库迁移工具migrate来创建数据库结构,和通过seed插入测试数据记录。

本文实例代码是基于当下最新的tp版本(8.0.3),应该也适用于tp5 和 tp6,如有需要自行按照本文思路进行实践验证即可。
ThinkPHP 官网地址:https://www.thinkphp.cn/
ThinkPHP8 官方手册:https://doc.thinkphp.cn/v8_0/preface.html
ThinkPHP6 官方手册:https://doc.thinkphp.cn/v6_1/default.html
ThinkPHP5.1 官方手册:https://doc.thinkphp.cn/v5_1/default.html
ThinkPHP5.0 官方手册:https://doc.thinkphp.cn/v5_0/default.html

Migrate 数据迁移

通过数据迁移工具 migrate 的创建数据表结构。

创建迁移

打开终端,并切换到 tp 项目根目录下,运行php think migrate:create Users 创建迁移文件后,打开创建的迁移文件并修改内容如下:

<?php

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

class Users 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('comment' => '最后登录时间'))
            ->addColumn('is_delete', 'boolean', array('limit' => 1, 'default' => 0, 'comment' => '删除状态,1已删除'))
            ->addIndex(array('username'), array('unique' => true))
            ->create();
    }
}

执行迁移

在 tp 项目根目录下,运行php think migrate:run,无报错则证明运行成功,此时查询数据库是否已创建 Users 表。

Seed 插入数据

创建 seed

在 tp 项目根目录下,运行php think seed:create Users 创建 seed 文件后,打开创建的 seed 文件并修改内容如下:

<?php

use Faker\Factory;
use think\migration\Seeder;

class Users 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(): void
    {
        $usersTable = $this->table('users');
        $usersTable->truncate();

        $faker = Factory::create('zh_CN');
        $users = [];
        for ($i = 0; $i < 109; $i++) {
            $users[] = [
                'username'        => substr($faker->userName(), -15),
                'login_status'    => $faker->randomElement(['0', '1']),
                // 'last_login_ip'   => $faker->ipv4(),
                'last_login_time' => date('Y-m-d') . ' ' . $faker->time()
            ];
        }

        $usersTable->insert($users)->save();

    }
}

执行 seed

在 tp 项目根目录下,运行php think seed:run,无报错则证明运行成功,此时查询 Users 表已插入 109 条测试数据。

声明:本文为原创文章,51blog.xyz和作者拥有版权,如需转载,请注明来源于51blog.xyz并保留原文链接:https://www.51blog.xyz/article/59.html

文章归档

推荐文章

buildadmin logo
Thinkphp8 Vue3 Element PLus TypeScript Vite Pinia

🔥BuildAdmin是一个永久免费开源,无需授权即可商业使用,且使用了流行技术栈快速创建商业级后台管理系统。

热门标签

PHP ThinkPHP ThinkPHP5.1 Go Mysql Mysql5.7 Redis Linux CentOS7 Git HTML CSS CSS3 Javascript JQuery Vue LayUI VMware Uniapp 微信小程序 docker wiki Confluence7 学习笔记 uView ES6 Ant Design Pro of Vue React ThinkPHP6.0 chrome 扩展 翻译工具 Nuxt SSR 服务端渲染 scrollreveal.js ThinkPHP8.0 Mac webman 跨域CORS vscode GitHub ECharts Canvas