Yii 将数据从一个模型复制到另一个模型
Yii copying data from one model to another
我是 yii 的新手。我使用由 CFormModel
扩展的模型从表单收集数据,在控制器内部我想将这些数据复制到从 CActiveRecord
扩展的模型,以便保存到数据库。有没有一种方法或方法可以将数据从数据收集模型复制到数据保存模型,而不是通过属性到属性来执行此操作,因为它太丑陋了。提前致谢。
您可以通过以下方式获取所有模型属性:
$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;
}
在圆顶组件中定义它,比如 UtilityComponent。
然后你可以调用 as
$modelTemp = $new ModelClass();
$model->someAttr = 'someVal';
$clonedModel = Yii::$app->utilities->cloneModel(ModelClass::class,$modelTemp);
我是 yii 的新手。我使用由 CFormModel
扩展的模型从表单收集数据,在控制器内部我想将这些数据复制到从 CActiveRecord
扩展的模型,以便保存到数据库。有没有一种方法或方法可以将数据从数据收集模型复制到数据保存模型,而不是通过属性到属性来执行此操作,因为它太丑陋了。提前致谢。
您可以通过以下方式获取所有模型属性:
$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;
}
在圆顶组件中定义它,比如 UtilityComponent。 然后你可以调用 as
$modelTemp = $new ModelClass();
$model->someAttr = 'someVal';
$clonedModel = Yii::$app->utilities->cloneModel(ModelClass::class,$modelTemp);