CodeIgnighter3でテーブルを自動生成する
マイグレーションでテーブルを作成してみる。
設定ファイルはapplication/config/migration.php
$config['migration_enabled'] = TRUE; $config['migration_type'] = 'sequential'; $config['migration_version'] = 1;
migration_enabledをTRUEにして有効にする。
デフォルトはタイムスタンプなので連番に変更。
application/migrations/フォルダを作成し、
設定ファイル001_add_tasks.phpを作成する。
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Migration_Add_tasks extends CI_Migration { public function up() { $this->dbforge->add_field(array( 'id' => array( 'type' => 'INT', 'unsigned' => TRUE, 'auto_increment' => TRUE ), 'title' => array( 'type' => 'VARCHAR', 'constraint' => '255', ), 'password' => array( 'type' => 'TEXT', 'null' => TRUE, ), )); $this->dbforge->add_key('id', TRUE); $this->dbforge->create_table('tasks'); } public function down() { $this->dbforge->drop_table('tasks'); } }
続いてコントローラーを作成する。
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()); } } }
ブラウザでhttp://localhost/index.php/migrate/に接続する。
tasksテーブルが作成される。
なお、同時にmigrationsテーブルも作成され、このテーブルでバージョン管理が行われる。