Last active
August 29, 2015 14:15
-
-
Save acodesmith/098673175afc1493f79d to your computer and use it in GitHub Desktop.
Map one model's values to another model. Yii 1
This file contains hidden or 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
/** | |
* Map any model attribute to another model attribute | |
* AR hasAttribute() required vs property_exist() | |
* @param $model1 | |
* @param $model2 | |
* @param $map array('id'=>'sku') The sku of the second model would map to the id of the first model | |
* @return array | |
*/ | |
function mapModelToModel($model1, $model2, $map) { | |
foreach ($map as $attr1 => $attr2) { | |
if ($model1->hasAttribute($attr1) && $model2->hasAttribute($attr2)) { | |
$model1->$attr1 = $model2->$attr2; | |
} | |
} | |
return array($model1, $model2); | |
} | |
/* Example */ | |
$shoes = new Shoes(); | |
$brand = ShoeBrands::model()->findByPk(1); | |
//Assuming Shoes contains two attributes called brand_id and brand_name | |
//The $shoes model will be returned with $brand->id set as $shoes->brand_id and $brand->name set as $shoes->brand_name | |
list($brand, $shoes) = mapModelToModel($brand, $shoes, array( 'brand_id'=>'id', 'brand_name'=>'name' )); | |
//This becomes very helpful when you are mapping large sets of (for example API) data to internal local tables. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment