遷移類
遷移是一種結(jié)構(gòu)化與有組織的方式來更改數(shù)據(jù)庫的方便方法。你可以手動(dòng)編輯 SQL 的片段,然后告知其他開發(fā)人員他們需要運(yùn)行這些片段。你還得保持追蹤他們的變化,追蹤那些下次部署時(shí)那些需要運(yùn)行但是會與生產(chǎn)設(shè)備沖突的變化。
數(shù)據(jù)庫表的 遷移 追蹤那些已經(jīng)運(yùn)行的遷移信息,你需要做的就是更新你的應(yīng)用文件并執(zhí)行 $this->migrate->current() 來計(jì)算出哪個(gè)遷移信息是需要被運(yùn)行的。遷移信息的當(dāng)前版本可以在這里 config/migration.php 找到。
創(chuàng)建一個(gè)遷移信息
這將是一個(gè) blog 站點(diǎn)的第一個(gè)遷移信息。所有的遷移信息都在文件夾 application/migrations/ 里,并且具有這樣的名稱,例如:001_add_blog.php.
defined('BASEPATH') OR exit('No direct script access allowed'); class Migration_Add_blog extends CI_Migration { public function up() { $this->dbforge->add_field(array( 'blog_id' => array( 'type' => 'INT', 'constraint' => 5, 'unsigned' => TRUE, 'auto_increment' => TRUE ), 'blog_title' => array( 'type' => 'VARCHAR', 'constraint' => '100', ), 'blog_description' => array( 'type' => 'TEXT', 'null' => TRUE, ), )); $this->dbforge->create_table('blog'); } public function down() { $this->dbforge->drop_table('blog'); }
然后在文件 application/config/migration.php 中設(shè)置 $config['migration_version'] = 1;。
使用范例
在該范例中,一些簡單的代碼被放置在 application/controllers/migrate.php 以更新架構(gòu)(schema)。
$this->load->library('migration'); if ( ! $this->migration->current()) { show_error($this->migration->error_string()); }
方法參考
$this->migration->current()
當(dāng)前的遷移信息是什么,被設(shè)置于 $config['migration_version'] 在文件 application/config/migration.php 中。
$this->migration->latest()
這個(gè)工作的和 current() 很像,但是不會從 $config['migration_version'] 尋找遷移信息,而是在文件系統(tǒng)中尋找最新的遷移信息。
$this->migration->version()
遷移版本可以用來回滾或前進(jìn)到特定版本。它工作起來像是 current() 但是會忽略 $config['migration_version'] 的設(shè)置。
$this->load->library('migration'); $this->migration->version(5);
遷移參數(shù)
以下是遷移類的配置選項(xiàng)列表。
參數(shù) | 默認(rèn)值 | 可選項(xiàng) | 描述 |
---|---|---|---|
migration_enabled | FALSE | TRUE / FALSE | 啟用或禁用遷移。 |
migration_version | 0 | None | 當(dāng)前數(shù)據(jù)庫所使用的版本。 |
migration_path | APPPATH.'migrations/' | None | 遷移信息所在路徑。 |
?