Last active
August 29, 2015 14:01
-
-
Save OdinsHat/52514bf443649e19e715 to your computer and use it in GitHub Desktop.
YII Migration example for copying fields from a related table by first creating them then copying the data over (thereby de-normalising it).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment