Thursday, December 18, 2014

Yii: Check Column Exists before Create Column with Migration Script

You need only 3 simple step to Create Column via Migration Script.

Step 1:
- Create Migration Script with yiic command:
- Goto project and run the following command


  1. protected/yiic migrate create alter_table_column

Step 2:
- Go to folder path protected/migrations and look for file name mxxxxxx_xxxxx_alter_table_column.php
- Add the following command in function up.


  1. public function up()
  2. {
  3. $table = Yii::app()->db->schema->getTable('table_name');
  4. if(!isset($table->columns['column_name'])) {
  5. // Column doesn't exist then create column
  6. $this->addColumn('table_name', 'column_name', 'int(11) NOT NULL');
  7. }
  8. }

Step 3:
- Run migration script with the following command:


  1. protected/yiic migrate
  2.  

~ EOF. Thanks for Reading. ~