Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii copying data from one model to another

Tags:

yii

I'm new to yii. I collect data from a form using a model extended by CFormModel and inside controller I want to copy these data to a model which is extended from CActiveRecord in order to save to DB. Is there a method or way to copy data from data collected model to data saving model rather than doing this by attribute to attribute as it's so ugly. Thanks in advance.

like image 338
Lasal Sethiya Avatar asked Jun 21 '15 06:06

Lasal Sethiya


2 Answers

you can get all models attributes by:

$data = $model->attributes;

and assign them to another model

$anotherModel = new AnotherActiveRecord();
$anotherModel->setAttributes($data);
$anotherModel->save();

now another model will extract whatever it can from $data

like image 121
Developerium Avatar answered Nov 11 '22 07:11

Developerium


You can use the following method

public function cloneModel($className,$model) {
    $attributes = $model->attributes;
    $newObj = new $className;
    foreach($attributes as  $attribute => $val) {
        $newObj->{$attribute} = $val;
    }
    return $newObj;
}

Define this in dome component , say UtilityComponent. Then you can call as

$modelTemp = $new ModelClass();
$model->someAttr = 'someVal';
$clonedModel = Yii::$app->utilities->cloneModel(ModelClass::class,$modelTemp);
like image 2
Jinu Joseph Daniel Avatar answered Nov 11 '22 06:11

Jinu Joseph Daniel