Hi all,
I have a model with a one-to-many relation. I’m trying to clone this model and its children all at once.
For this I use:
$newModel = clone $oldModel;
$newModel->isNewRecord = true;
unset ($newModel->id);
$newModel->save();
This works fine for copying the parent record however its children are not copied.
I have verified that they are loaded in $oldModel.
Can anyone point me in the right direction for the most elegant solution to solve this?
Thanks a lot!
My solution for now:
In the parent and child model I created a __clone method:
public function __clone() {
unset ($this->id);
$this->isNewRecord = true;
}
In the controller:
public function actionCreateFromLast()
{
$lastModel= TheParent::model()->find(...);
$model = clone $lastModel;
$model->save();
if (!empty($lastModel->children)) {
foreach ($lastModel->children as $child) {
$newChild = clone $child;
$newChild->parentId = $model->id;
$newChild->save();
}
}
return;
}
Seems to work fine.
ladamalina
(Nadezhdaryabtsova)
3
Good work. Did you try to move foreach block to mentioned __clone method? Seems a bit more elegant.