2015-06-21 103 views
3

我是yii的新手。我使用擴展模型CFormModel和內部控制器收集表單中的數據,我想將這些數據複製到從CActiveRecord擴展的模型中,以保存到數據庫。有沒有一種方法或方法可以將數據從數據收集模型複製到數據保存模型,而不是通過屬性將屬性設置爲屬性,因爲它非常難看。提前致謝。Yii將數據從一個模型複製到另一個模型

回答

15

你可以得到所有型號的屬性是:

$data = $model->attributes; 

,並將它們分配到另一個模型

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

現在另一種模型將提取任何它可以從$data

0

可以使用以下方法

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

在圓頂組件中定義它,例如UtilityComponent。 然後您可以撥打電話

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