Thinkphp 数据库迁移和填充
Posted IronMenPHP
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Thinkphp 数据库迁移和填充相关的知识,希望对你有一定的参考价值。
一.thinkphp 数据库迁移
1.首先通过 composer 安装 tp5.1
composer require topthink/think-migration=2.0.*
2.创建迁移文件
php think migrate:create Users
3.编辑文件
public function change()
{
// create the table
$table = $this->table('users',array('engine'=>'InnoDB','comment' => '用户表'));
$table->addColumn('username', 'string',array('limit' => 32,'default'=>'','comment'=>'用户名,登陆使用'))
->addColumn('password', 'string',array('limit' => 32,'default'=>md5('123456'),'comment'=>'用户密码'))
->addColumn('name', 'string',array('limit' => 32,'default'=>'','comment'=>'真实姓名'))
->addColumn('phonenum', 'integer',array('limit' => 32,'default'=>110,'comment'=>'手机号'))
->addColumn('email', 'string',array('limit' => 32,'default'=>'122843744@qq.com','comment'=>'邮箱'))
->addColumn('role_id', 'string',array('limit' => 32,'default'=>'122843744@qq.com','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))
->addTimestamps()
->create();
}
public function up()
{
// add column type DOUBLE
$this->execute("ALTER TABLE third ADD COLUMN much_money DOUBLE(10,2) unsigned NOT NULL DEFAULT '0.00'");
}
public function down()
{
$this->dropTable('users');
}
4.执行文件迁移
php think migrate:run
5.执行回滚
php think migrate:rollback -t third
二.thinkphp 数据填充
1.创建填充
php think seed:create Third
2.编辑填充文件
public function run()
{
$data[] = [
'username' => $faker->userName,
'name' => $faker->name,
'phonenum' => $faker->phoneNumber,
'email' => $faker->email,
'role_id' => 3
];
}
3.开始进行数据库填充
a. php think seed:run
b.可指定一个或多个 seed
c. $ php think seed:run -s Third
$ php think seed:run -s Third -s member
4.安装faker类库
composer require fzaninotto/faker
public function run()
{
$faker = Factory::create('zh_CN');//选择中文库
$data = [];
for ($i = 0; $i < 100; $i++) {
$data[] = [
'username' => $faker->userName,
'name' => $faker->name,
'phonenum' => $faker->phoneNumber,
'email' => $faker->email,
'role_id' => 3
];
}
$this->table('users')->insert($data)->save();
}
以上是关于Thinkphp 数据库迁移和填充的主要内容,如果未能解决你的问题,请参考以下文章