Thinkphp5 數據遷移(think-migration) 轉

數據庫遷移工具

首先通過 composer 安裝

composer require topthink/think-migration

注意事項,不支持修改文件配置目錄

在命令行下運行查看幫助,可以看到新增的命令

php think 
 migrate
  migrate:create     Create a new migration
  migrate:rollback   Rollback the last or to a specific migration
  migrate:run        Migrate the database
  migrate:status     Show migration status
 optimize
  optimize:autoload  Optimizes PSR0 and PSR4 packages to be loaded wit
h classmaps too, good for production.
  optimize:config    Build config and common file cache.
  optimize:route     Build route cache.
  optimize:schema    Build database schema cache.
 seed
  seed:create        Create a new database seeder
  seed:run           Run database seeders

創建遷移類,首字母必須爲大寫

php think migrate:create Users

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

使用實例

<?php

use Phinx\Migration\AbstractMigration;

class Users extends AbstractMigration
{
    /**
     * Change Method.
     */
    public function change()
    {
        // create the table
        $table = $this->table('users',array('engine'=>'MyISAM'));
        $table->addColumn('username', 'string',array('limit' => 15,'default'=>'','comment'=>'用戶名,登陸使用'))
            ->addColumn('password', 'string',array('limit' => 32,'default'=>md5('123456'),'comment'=>'用戶密碼'))
            ->addColumn('login_status', 'boolean',array('limit' => 1,'default'=>0,'comment'=>'登陸狀態'))
            ->addColumn('login_code', 'string',array('limit' => 32,'default'=>0,'comment'=>'排他性登陸標識'))
            ->addColumn('last_login_ip', 'integer',array('limit' => 11,'default'=>0,'comment'=>'最後登錄IP'))
            ->addColumn('last_login_time', 'datetime',array('default'=>0,'comment'=>'最後登錄時間'))
            ->addColumn('is_delete', 'boolean',array('limit' => 1,'default'=>0,'comment'=>'刪除狀態,1已刪除'))
            ->addIndex(array('username'), array('unique' => true))
            ->create();
    }

    /**
     * Migrate Up.
     */
    public function up()
    {

    }

    /**
     * Migrate Down.
     */
    public function down()
    {

    }
}


對於同一個數據表,如果需要新的遷移動作,例如刪除字段、創建字段,可以創建新的更改文件,像svn一樣往前記錄操作,方便回滾。

更具體的使用可查看

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

Thinkphp5中migrate數據庫遷移工具詳解

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章