数据库迁移功能使用第三方库 robmorgan/phinx
gitHub地址: https://github.com/cakephp/phinx
官方文档: https://tsy12321.gitbooks.io/phinx-doc/content/commands.html
使用说明
# 安装Phinx:
composer require robmorgan/phinx
# Phinx 初始化
vendor/bin/phinx init
# 在你项目目录中创建目录 db/migrations ,并给予充足权限。
# 这个目录将是你迁移脚本放置的地方,并且应该被设置为可写权限。
# 创建表
vendor/bin/phinx create CreateWechatUserTable
# 修改表
vendor/bin/phinx create AddNameToWechatUserTable
# 执行数据迁移
vendor/bin/phinx migrate
# 回滚
vendor/bin/phinx rollback
env()方法支持
为了在数据迁移中复用 .env 中的数据库配置,需要在phinx.php文件中做如下改动
<?php
# 引入env支持
use Dotenv\Dotenv;
if (method_exists('Dotenv\Dotenv', 'createUnsafeImmutable')) {
Dotenv::createUnsafeImmutable(base_path())->load();
} else {
Dotenv::createMutable(base_path())->load();
}
return
[
'paths' => [
'migrations' => '%%PHINX_CONFIG_DIR%%/db/migrations',
'seeds' => '%%PHINX_CONFIG_DIR%%/db/seeds'
],
'environments' => [
'default_migration_table' => 'phinxlog',
'default_environment' => 'production',
'production' => [
'adapter' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'name' => env('DB_DATABASE', 'forge'),
'user' => env('DB_USERNAME', 'forge'),
'pass' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
],
'development' => [
'adapter' => 'mysql',
'host' => 'localhost',
'name' => 'development_db',
'user' => 'root',
'pass' => '',
'port' => '3306',
'charset' => 'utf8',
],
'testing' => [
'adapter' => 'mysql',
'host' => 'localhost',
'name' => 'testing_db',
'user' => 'root',
'pass' => '',
'port' => '3306',
'charset' => 'utf8',
]
],
'version_order' => 'creation'
];