LoginSignup
33
37

More than 5 years have passed since last update.

Codeigniterのmigration

Last updated at Posted at 2013-12-11

僕も日頃Codeigniterにお世話になっているので参加です。
日本語のユーザーガイドのバージョンが古く、migrationについては英語のユーザーガイドしかありませんので、簡単に説明します。

dbforgeと組み合わせて利用されます。
dbforgeについては日本語ガイドがあるのでそちらを参照。
http://codeigniter.jp/user_guide_ja/database/forge.html

まずmigrationファイルを格納するディレクトリを作成します

application/migrations

config/migrations.phpで設定できますが上記がデフォルトです。

次に作成したディレクトリにファイルを作成します。

application/migrations/001_add_blog.php

注意点としては頭に3桁0埋めで数字を入れてください。
これがバージョンの数字になります。

001_add_blog.php
class Migration_Add_blog extends CI_Migration {

    public function __construct()
    {
        parent::__construct();
    }
    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->add_key('blog_id', true);
        $this->dbforge->create_table('blog');
    }

    public function down()
    {
        $this->dbforge->drop_table('blog');
    }
}

CI_Migrationのコンストラクタでdbforgeは呼び出されているので、こちらで呼び出す必要はありません。

クラス名はファイル名から推測されるようになっているので注意です。
Migration_[バージョン番号を除いたファイル名の頭大文字]
例)
001_add_blog.php -> Migration_Add_blog

up()にバージョンを上げるときの実行内容、
down()にバージョンを下げるときの実行内容を記述します。

次に現在のmigrationのバージョンを設定します。

application/config/migration.php
$config['migration_enabled'] = TRUE;
$config['migration_version'] = 1;

最後にmigrationを実行します。
コマンドラインから実行したいのでその用意をします。

application/controller/migrate.php
class Migrate extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        // コマンドラインから実行されていることを確認
        if(!$this->input->is_cli_request()) {
            show_error();
        }
        $this->load->library('migration');
    }

    function current()
    {
        $this->migration->current();
    }

    function rollback($version)
    {
        $this->migration->version($version);
    }

    function latest()
    {
        $this->migration->latest();
    }

}

コマンドラインからの実行チェックを忘れないようにしましょう。
プロジェクトのルートに移動し、以下を実行します。

php index.php migrate current

これでconfigファイルで設定したバージョンまで実行されます。
rollback()は引数に指定したバージョンまで戻します。
latest()はconfigに関係なくmigrations/下にあるファイルの最新まで実行されます。

以上ですが簡単な説明になります。
実装が最小限なのでmigrationとはなんぞやというところがわかりやすいですね。
dbforgeを利用していますが、sqlを普通に実行することもできます。
あくまでdbforgeとmigrationは別物です。

英語版ユーザーガイド
http://ellislab.com/codeigniter%20/user-guide/libraries/migration.html

33
37
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
37