OdinsHat
5/9/2014 - 10:28 PM

YII Migration example for copying fields from a related table by first creating them then copying the data over (thereby de-normalising it).

YII Migration example for copying fields from a related table by first creating them then copying the data over (thereby de-normalising it).

<?php
/**
 * This is an obfuscated Yii Migration example taken from a commercial project I'm working on.
 * 
 * I thought I may find the creation of fields in one table and 
 * copying over of the data from the related table (thereby de-normalising it) 
 * of some use in future. It was required in a few tables due to the unusual 
 * nature of the related data.
 * 
 * @see http://www.yiiframework.com/doc/guide/1.1/en/database.migration
 */

class m102030_010203_add_fields_to_table extends CDbMigration
{
    public function safeUp()
    {
        $this->addColumn('tablename', 'field1', 'varchar(32)');
        $this->addColumn('tablename', 'field2', 'varchar(32)');
        $this->addColumn('tablename', 'field3', 'varchar(32)');
        $this->addColumn('tablename', 'field4', 'varchar(32)');
        $this->addColumn('tablename', 'field5', 'tinyint(1)');

        $this->execute('UPDATE tablename SET tablename.field1 = (SELECT tablename2.field1 FROM tablename2 WHERE tablename.tb2_id = tablename2.id)');
        $this->execute('UPDATE tablename SET tablename.field2 = (SELECT tablename2.field2 FROM tablename2 WHERE tablename.tb2_id = tablename2.id)');
        $this->execute('UPDATE tablename SET tablename.field3 = (SELECT tablename2.field3 FROM tablename2 WHERE tablename.tb2_id = tablename2.id)');
        $this->execute('UPDATE tablename SET tablename.field4 = (SELECT tablename2.field4 FROM tablename2 WHERE tablename.tb2_id = tablename2.id)');
        $this->execute('UPDATE tablename SET tablename.field5 = (SELECT tablename2.field5 FROM tablename2 WHERE tablename.tb2_id = tablename2.id)');
    }

    public function safeDown()
    {
        $this->dropColumn('tablename', 'field1');
        $this->dropColumn('tablename', 'field2');
        $this->dropColumn('tablename', 'field3');
        $this->dropColumn('tablename', 'field4');
        $this->dropColumn('tablename', 'field5');
    }
}