Yii copying data from one model to another

徘徊边缘 提交于 2019-12-12 12:35:35

问题


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.


回答1:


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




回答2:


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);


来源:https://stackoverflow.com/questions/30961807/yii-copying-data-from-one-model-to-another

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!