Yii将数据从一个模型复制到另一个模型

Yii将数据从一个模型复制到另一个模型,yii,Yii,我是yii的新手。我使用由CFormModel扩展的模型从表单收集数据,在控制器内部,我想将这些数据复制到从CActiveRecord扩展的模型,以便保存到DB。有没有一种方法或方法可以将数据从数据收集模型复制到数据保存模型,而不是按属性进行复制,因为这样做太难看了。提前谢谢 您可以通过以下方式获取所有模型属性: $data = $model->attributes; 并将它们分配给另一个模型 $anotherModel = new AnotherActiveRecord(); $ano

我是yii的新手。我使用由
CFormModel
扩展的模型从表单收集数据,在控制器内部,我想将这些数据复制到从
CActiveRecord
扩展的模型,以便保存到DB。有没有一种方法或方法可以将数据从数据收集模型复制到数据保存模型,而不是按属性进行复制,因为这样做太难看了。提前谢谢

您可以通过以下方式获取所有模型属性:

$data = $model->attributes;
并将它们分配给另一个模型

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

现在,另一个模型将从
$data

中提取任何可以提取的数据。您可以使用以下方法

public function cloneModel($className,$model) {
    $attributes = $model->attributes;
    $newObj = new $className;
    foreach($attributes as  $attribute => $val) {
        $newObj->{$attribute} = $val;
    }
    return $newObj;
}
在dome组件中定义此项,例如UtilityComponent。 然后你可以打电话给我

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

在Laravel的更高版本中,这应该是
$data=$model->attributesToArray()
$anotherModel->setrawtattributes($data)