Thinkphp5 数据迁移

数据库迁移工具

首先通过 composer 安装

composer require topthink/think-migration

注意事项,不支持修改文件配置目录

在命令行下运行查看帮助,可以看到新增的命令

php think 
migrate
migrate:create Create a new migration
migrate:rollback Rollback the last or to a specific migration
migrate:run Migrate the database
migrate:status Show migration status
optimize
optimize:autoload Optimizes PSR0 and PSR4 packages to be loaded wit
h classmaps too, good for production.
optimize:config Build config and common file cache.
optimize:route Build route cache.
optimize:schema Build database schema cache.
seed
seed:create Create a new database seeder
seed:run Run database seeders

创建迁移类,首字母必须为大写

php think migrate:create Users

可以看到目录下有新文件 .\database\migrations\20161117144043_users.php

使用实例

use Phinx\Migration\AbstractMigration;
class Users extends AbstractMigration
{
/**
* Change Method.
*/
public function change()
{
// create the table
$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('default'=>0,'comment'=>'最后登录时间'))
->addColumn('is_delete', 'boolean',array('limit' => 1,'default'=>0,'comment'=>'删除状态,1已删除'))
->addIndex(array('username'), array('unique' => true))
->create();
}
/**
* Migrate Up.
*/
public function up()
{
}
/**
* Migrate Down.
*/
public function down()
{
}
}

对于同一个数据表,如果需要新的迁移动作,例如删除字段、创建字段,可以创建新的更改文件,像svn一样往前记录操作,方便回滚。


分享到:


相關文章: