问题
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