Fawzan
Fawzan

Reputation: 4849

Codeigniter Migration to Alter a Table

I have crated a Migration in codeigniter to create a MySQL table with 4 columns. Now I want to change the name of one of the columns without losing the data in that table.

First, I have enabled migration & set the version to 1. Then, I have created a file 001_create_users.php and added the following code.

class Migration_Create_users extends CI_Migration {

    public function up(){

        $this->dbforge->add_field(
            array(
                'id'        => array('type'=>'INT', 'constraint'=>11, 'unsigned'=>TRUE, 'auto_increment'=>TRUE),
                'email'     => array('type'=>'VARCHAR', 'constraint'=>100),
                'password'  => array('type'=>'VARCHAR', 'constraint'=>255),
                'created'      => array('type'=>"TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
            )
        );

        $this->dbforge->add_key('id');
        $this->dbforge->create_table('users');

    }

    public function down(){

        $this->dbforge->drop_table('users');

    }
}

Now I want to change the column name 'date' to 'created_at'. So how should I do it? I mean what is the best way to do it? Also can anyone explain me how to do a rollback? Because I have used the folwing controller to run the migration.

class Migration extends Admin_Controller{

    public function __construct(){
        parent::__construct();
    }

    public function index($version){

        $this->load->library('migration');

        if( !$this->migration->version($version)){
            show_error($this->migration->error_string());
        }
        echo "I'm in Migration";
    }

}

So, If I run http://localhost/migration/index/1 It will run the up() function. What should I do to perform a rollback via browser? Can I create another method and call it?

I still do not understand how the migration actually works, Can anyone please explain it to me?

Upvotes: 1

Views: 7354

Answers (1)

Runish Kumar
Runish Kumar

Reputation: 194

You can try browsing http://localhost/migration/index/0 to go back to version 0. OR you can create separate function 'rollback' to rollback to a specific version and make index function to migrate up only using $this->migration->current()

Upvotes: 2

Related Questions