Yii copying data from one model to another

I am new to yii. I am collecting data from a form using a model extended CFormModel

and inside a controller. I want to copy this data into a model that is extended with CActiveRecord

in order to save it to the DB. Is there a way or a way to copy the data from the data model compiled into the persistence model instead of making it an attribute of an attribute as it is so ugly. Thank you in advance.

+3


source to share


2 answers


You can get all the attributes of the models:

$data = $model->attributes;

      

and assign them to another model



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

      

now another model will fetch whatever it can from $data

+19


source


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 a dome component such as a UtilityComponent. Then you can call like

$modelTemp = $new ModelClass();
$model->someAttr = 'someVal';
$clonedModel = Yii::$app->utilities->cloneModel(ModelClass::class,$modelTemp);

      

0


source







All Articles