Skip to content
This repository has been archived by the owner on Dec 23, 2021. It is now read-only.

Using migrations

sjlu edited this page May 29, 2012 · 2 revisions

Migrations help you keep database schemas in sync throughout all environment or servers that you may have. This also allows you to keep your developer's MySQL environments in sync too without needing to worry about MySQL dumps.

Steps

  1. Create your first migration file in the folder application/migrations, you should name it something like 001_Initial.php. You need to make sure you have the three digit number in prefixed to the filename.
  2. Write in that migration file with the following class structure. Note here that the filename must match the end of the class name or CodeIgniter will complain.
<?php
class Migration_Initial extends CI_Migration {
   function up() { }
   function down() { }
}
?>
  1. Use the Database Forge class that CodeIgniter includes to modify your database structure.
  2. Modify the file application/config/migration.php. Set the appropriate variables.
$config['migration_enabled'] = TRUE;
$config['migration_version'] = 1;
  1. In your models, you should have the following to make sure your migration takes place.
$this->load->library('migration');
if (!$this->migration->current())
   show_error($this->migration->error_string());

Example

<?php
class Migration_Create extends CI_Migration {

   public function up()
   {
		$fields = array(
			'session_id' => array(
				'type' => 'VARCHAR',
				'constraint' => '32',
			),
			'user_agent' => array(
				'type' => 'VARCHAR',
				'constraint' => '255',
				'null' => true,
			),
			'ip_address' => array(
				'type' => 'VARCHAR',
				'constraint' => '20',
				'null' => true,
			),
			'last_activity' => array(
				'type' => 'INT',
				'constraint' => '12',
				'null' => true,
			),
			'user_data' => array(
				'type' => 'TEXT',
			),
		);

		$this->dbforge->add_field($fields);
		$this->dbforge->add_key('session_id', TRUE);
		$this->dbforge->create_table('ci_sessions');
   }


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

}

Reference

http://codeigniter.com/user_guide/libraries/migration.html

Clone this wiki locally