数据库迁移工具

首先通过 composer 安装

  1. composer require topthink/think-migration

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


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

  1. php think
  1. migrate
  2. migrate:create Create a new migration
  3. migrate:rollback Rollback the last or to a specific migration
  4. migrate:run Migrate the database
  5. migrate:status Show migration status
  6. optimize
  7. optimize:autoload Optimizes PSR0 and PSR4 packages to be loaded wit
  8. h classmaps too, good for production.
  9. optimize:config Build config and common file cache.
  10. optimize:route Build route cache.
  11. optimize:schema Build database schema cache.
  12. seed
  13. seed:create Create a new database seeder
  14. seed:run Run database seeders

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

  1. php think migrate:create Users

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

使用实例

  1. <?php
  2. use Phinx\Migration\AbstractMigration;
  3. class Users extends AbstractMigration
  4. {
  5. /**
  6. * Change Method.
  7. */
  8. public function change()
  9. {
  10. // create the table
  11. $table = $this->table('users',array('engine'=>'MyISAM'));
  12. $table->addColumn('username', 'string',array('limit' => 15,'default'=>'','comment'=>'用户名,登陆使用'))
  13. ->addColumn('password', 'string',array('limit' => 32,'default'=>md5('123456'),'comment'=>'用户密码'))
  14. ->addColumn('login_status', 'boolean',array('limit' => 1,'default'=>0,'comment'=>'登陆状态'))
  15. ->addColumn('login_code', 'string',array('limit' => 32,'default'=>0,'comment'=>'排他性登陆标识'))
  16. ->addColumn('last_login_ip', 'integer',array('limit' => 11,'default'=>0,'comment'=>'最后登录IP'))
  17. ->addColumn('last_login_time', 'datetime',array('default'=>0,'comment'=>'最后登录时间'))
  18. ->addColumn('is_delete', 'boolean',array('limit' => 1,'default'=>0,'comment'=>'删除状态,1已删除'))
  19. ->addIndex(array('username'), array('unique' => true))
  20. ->create();
  21. }
  22. /**
  23. * Migrate Up.
  24. */
  25. public function up()
  26. {
  27. }
  28. /**
  29. * Migrate Down.
  30. */
  31. public function down()
  32. {
  33. }
  34. }

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

更具体的使用可查看

http://docs.phinx.org/en/latest/