本文实例代码是基于当下最新的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
的创建数据表结构。
打开终端,并切换到 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 表。
在 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();
}
}
在 tp 项目根目录下,运行php think seed:run
,无报错则证明运行成功,此时查询 Users 表已插入 109 条测试数据。