Codeigniter3でブログサンプルを作成No.1
CodeIgniter3でブログアプリを作ってみる。
まずはMigration機能でテーブルを作成する。
(database.phpの設定は省略)
開発環境
MacOS X Yosemite MAMP 3.3 CodeIgniter3.0
作成するテーブル(blog)
Name | Type | Null | Default | Extra |
---|---|---|---|---|
id | int(5) | No | None | AUTO_INCREMENT |
title | varchar(100) | No | None | |
description | text | Yes | Null | |
created_at | timestamp | No | CURRENT_TIMESTAMP | |
updated_at | timestamp | No | 0000-00-00 00:00:00 |
設定ファイルを修正
application/config/migration.phpの修正
<?php // Migrationを有効にする $config['migration_enabled'] = TRUE; // タイムスタンプではなく連番にする $config['migration_type'] = 'sequential'; // バージョン番号を1にする $config['migration_version'] = 1;
テーブル情報を追加
application/migrations/001_add_blog.php
<?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( 'id' => array( 'type' => 'INT', 'constraint' => '5', 'unsigned' => TRUE, 'auto_increment' => TRUE, ), 'title' => array( 'type' => 'VARCHAR', 'constraint' => '100', ), 'description' => array( 'type' => 'TEXT', 'null' => TRUE, ), 'created_at' => array( 'type' => 'TIMESTAMP', ), 'updated_at' => array( 'type' => 'TIMESTAMP', ), )); $this->dbforge->add_key('id', TRUE); $this->dbforge->create_table('blog'); } public function down() { $this->dbforge->drop_table('blog'); } }
TIMESTAMPは最初に設定したカラムにCURRENT_TIMESTAMPが設定されるらしい。
次にMigrationを実行するためにコントローラを作成する。
コントローラ
application/controllers/Migrate.pp
<?php defined('BASEPATH') OR exit('No direct script access allowed'); 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:8888/index.php/migrateを開くとblogとmigrationsの2つのテーブルが作成される。
参考)公式ドキュメント
Migrations Class — CodeIgniter 3.0.0-dev documentation