LoginSignup
6

More than 5 years have passed since last update.

Codeigniter3のMigrationでテーブル作成。

Last updated at Posted at 2015-05-21

Codeigniter3のマイグレーションでテーブルを作ってみる。

Codeigniter3はComposerでインストール済み

データベース設定

Vagrantで試したのでポート番号追記

config/database.php
$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => 'root',
    'database' => 'test',
    'dbdriver' => 'mysqli',
        ・・・
    'port' => 3306
);

マイグレーション設定

今回はファイルに連番をつけてやる設定で。

config/migrate.php
$config['migration_enabled'] = TRUE;// 有効
$config['migration_type']    = 'sequential';// 連番 or タイムスタンプ
$config['migration_version'] = 1; // バージョン

マイグレーションファイル作成

今回はバージョンを1としますのでファイル名に001を振ります。

migrations/001_add_users.php
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_Add_Users extends CI_Migration
{

    public function up()
    {
        $this->dbforge->add_field([
                                      'id'       => [
                                          'type'           => 'INT',
                                          'unsigned'       => TRUE,
                                          'auto_increment' => TRUE
                                      ],
                                      'email'    => [
                                          'type'       => 'VARCHAR',
                                          'constraint' => '255',
                                      ],
                                      'password' => [
                                          'type'       => 'VARCHAR',
                                          'constraint' => '255',
                                      ],
                                  ]);
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('users');
    }

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

マイグレーションコントローラー作成

application/controllers/Migrate.php
<?php

class Migrate extends CI_Controller
{

    public function index()
    {
        $this->load->library('migration');

        if ($this->migration->current() === FALSE) {
            show_error($this->migration->error_string());
        }
    }

}

マイグレーション実行

vagrant sshでサーバーに入ります。
index.phpを設置したディレクトリに移動します。

cd public
php index.php migrate

usersテーブルが作成されました。

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
6