数据库迁移功能使用第三方库 robmorgan/phinx

gitHub地址: https://github.com/cakephp/phinx

官方文档: https://tsy12321.gitbooks.io/phinx-doc/content/commands.html

使用说明

  1. # 安装Phinx:
  2. composer require robmorgan/phinx
  3. # Phinx 初始化
  4. vendor/bin/phinx init
  5. # 在你项目目录中创建目录 db/migrations ,并给予充足权限。
  6. # 这个目录将是你迁移脚本放置的地方,并且应该被设置为可写权限。
  7. # 创建表
  8. vendor/bin/phinx create CreateWechatUserTable
  9. # 修改表
  10. vendor/bin/phinx create AddNameToWechatUserTable
  11. # 执行数据迁移
  12. vendor/bin/phinx migrate
  13. # 回滚
  14. vendor/bin/phinx rollback

env()方法支持

为了在数据迁移中复用 .env 中的数据库配置,需要在phinx.php文件中做如下改动

  1. <?php
  2. # 引入env支持
  3. use Dotenv\Dotenv;
  4. if (method_exists('Dotenv\Dotenv', 'createUnsafeImmutable')) {
  5. Dotenv::createUnsafeImmutable(base_path())->load();
  6. } else {
  7. Dotenv::createMutable(base_path())->load();
  8. }
  9. return
  10. [
  11. 'paths' => [
  12. 'migrations' => '%%PHINX_CONFIG_DIR%%/db/migrations',
  13. 'seeds' => '%%PHINX_CONFIG_DIR%%/db/seeds'
  14. ],
  15. 'environments' => [
  16. 'default_migration_table' => 'phinxlog',
  17. 'default_environment' => 'production',
  18. 'production' => [
  19. 'adapter' => 'mysql',
  20. 'host' => env('DB_HOST', '127.0.0.1'),
  21. 'port' => env('DB_PORT', '3306'),
  22. 'name' => env('DB_DATABASE', 'forge'),
  23. 'user' => env('DB_USERNAME', 'forge'),
  24. 'pass' => env('DB_PASSWORD', ''),
  25. 'charset' => 'utf8',
  26. ],
  27. 'development' => [
  28. 'adapter' => 'mysql',
  29. 'host' => 'localhost',
  30. 'name' => 'development_db',
  31. 'user' => 'root',
  32. 'pass' => '',
  33. 'port' => '3306',
  34. 'charset' => 'utf8',
  35. ],
  36. 'testing' => [
  37. 'adapter' => 'mysql',
  38. 'host' => 'localhost',
  39. 'name' => 'testing_db',
  40. 'user' => 'root',
  41. 'pass' => '',
  42. 'port' => '3306',
  43. 'charset' => 'utf8',
  44. ]
  45. ],
  46. 'version_order' => 'creation'
  47. ];