给 PHP 项目添加数据库迁移
给 PHP 项目添加数据库迁移
旧 PHP 项目的数据库迁移,很多直接使用 SQL 语句来记录,这种方式实在很不方便,所以介绍一个数据库迁移工具:Phinx。
特点
- 使用 PHP 代码写数据库迁移
- 数据库迁移执行和回滚
- 数据库迁移部署
- 创建数据库数据
- 和任何应用都能集成
支持数据库
MySQL
PostgreSQL
SQLite
Microsoft SQL Server
安装
-
安装 Composer
curl -sS https://getcomposer.org/installer | php
-
添加库 Phinx
php composer.phar require robmorgan/phinx
-
运行 Composer
php composer.phar install --no-dev
-
初始化 Phinx, 生成配置文件
phinx.yml
php vendor/bin/phinx init
配置文件内容:
paths: migrations: %%PHINX_CONFIG_DIR%%/db/migrations seeds: %%PHINX_CONFIG_DIR%%/db/seeds environments: default_migration_table: phinxlog default_database: development development: adapter: mysql host: localhost name: artable user: root pass: '' port: 3306 charset: utf8
使用 Migration
创建一个新的迁移
php vendor/bin/phinx create MyNewMigration
迁移文件:
<?php
use Phinx\Migration\AbstractMigration;
class MyNewMigration extends AbstractMigration
{
/**
* Change Method.
*
* Write your reversible migrations using this method.
*
* More information on writing migrations is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
*
* The following commands can be used in this method and Phinx will
* automatically reverse them when rolling back:
*
* createTable
* renameTable
* addColumn
* renameColumn
* addIndex
* addForeignKey
*
* Remember to call "create()" or "update()" and NOT "save()" when working
* with the Table class.
*/
public function change()
{
}
}
基本字段类型
- biginteger
- binary
- boolean
- date
- datetime
- decimal
- float
- integer
- string
- text
- time
- timestamp
- uuid
不同的数据有各自不同的类型,具体请看 文档
例子:添加字段
<?php
use Phinx\Migration\AbstractMigration;
class CreateUserLoginsTable extends AbstractMigration
{
/**
* Change Method.
*
* More information on this method is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-change-method
*
* Uncomment this method if you would like to use it.
*/
public function change()
{
// create the table
$table = $this->table('user_logins');
$table->addColumn('user_id', 'integer')
->addColumn('created_at', 'datetime')
->create();
}
}
运行 Migration
php vendor/bin/phinx migrate -e development
development
是指定执行的环境,如:development
, production
, test
指定某个版本使用 --target
或者 -t
php vendor/bin/phinx migrate -e development -t 20110103081132
回滚 Migration
php vendor/bin/phinx rollback -e development
资源
本帖已被设为精华帖!
本帖由 Summer
于 8年前 加精
phpmig
也不错Phinx 很强大
老铁知不知道怎么创建biginteger的主键?