使用phinx做database migration

楚天乐 303 0 条

安装

使用compose安装, 命令

php composer.phar require robmorgan/phinx

项目根目录创建db/migrations文件夹,然后执行如下命令(windows系统)

λ vendor\bin\phinx init

此时根目录生成了phinx.yml文件。打开修改数据库连接信息,此处我们只设置development数据库连接

paths:
    migrations: '%%PHINX_CONFIG_DIR%%/db/migrations'
    seeds: '%%PHINX_CONFIG_DIR%%/db/seeds'

environments:
    default_migration_table: phinxlog
    default_database: development
    production:
        adapter: mysql
        host: localhost
        name: production_db
        user: root
        pass: ''
        port: 3306
        charset: utf8

    development:
        adapter: mysql
        table_prefix: prod_    # 增加表名前缀
        host: 127.0.0.1
        name: dbname
        user: root
        pass: '123456'
        port: 3306
        charset: utf8

    testing:
        adapter: mysql
        host: localhost
        name: testing_db
        user: root
        pass: ''
        port: 3306
        charset: utf8

version_order: creation

操作

Migration操作

  1. 创建Migration。
    vendor\robmorgan\phinx\bin\phinx create MyNewMigration # 创建一个migration

    此操作会在db\migrations目录下创建xxxx_my_new_migration.php,我们只需要在里面实现change(),或者up()和down()即可达到目的。文件内容大致内容如下:

    
    <?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
  • addCustomColumn
  • renameColumn
  • addIndex
  • addForeignKey
  • Any other destructive changes will result in an error when trying to
  • rollback the migration.
  • Remember to call "create()" or "update()" and NOT "save()" when working
  • with the Table class.
    */
    public function change()
    {

    }
    }


2. 执行migration

vendor\bin\phinx migrate -e development


3. 回滚migration

回滚

vendor\bin\phinx rollback -e development

回滚到特定节点

vendor\bin\phinx rollback -e development -t 20120103083322

#### table操作
创建表

$quote = $this->table('quote');
$quote->addColumn('firstname', 'string', ['null' => false, 'limit' => 255])
->addColumn('lastname', 'string', ['null' => false, 'limit' => 255])
->addColumn('email', 'string', ['null' => false, 'limit' => 255])
->addColumn('telephone', 'string', ['null' => false, 'limit' => 255])
->addColumn('description', 'text')
->addColumn('ip', 'string', ['null' => false, 'limit' => 255])
->addColumn('source', 'string', ['null' => false, 'limit' => 255])
->create();


删除表,非常直白,不多说

$this->table('tuangou_products')->drop()->save();



添加字段

删除字段

修改字段

#### column操作

#### 查询


发表我的评论
'
昵称 (必填)
邮箱 (必填)
网址