Skip to content

Instantly share code, notes, and snippets.

@iJackUA
Last active March 24, 2019 10:43
Show Gist options
  • Save iJackUA/6636ac60b763fdc1d14560e8900f8789 to your computer and use it in GitHub Desktop.
Save iJackUA/6636ac60b763fdc1d14560e8900f8789 to your computer and use it in GitHub Desktop.
Yii 1. Clone AR model and Relations
<?php
namespace common\models\traits;
trait ActiveRecordClone
{
/**
* Return new record with cloned attributes
*
* @param string $scenario
* @return static
*/
public function cloneModel($scenario = 'insert')
{
/** @var \CActiveRecord $newModel */
$newModel = new static($scenario);
/** @var \CModel $this */
$newModel->setAttributes($this->getAttributes($this->getSafeAttributeNames()));
return $newModel;
}
/**
* Clone related records and attach to current model
*
* @param static $originModel Model where to take original related data
* @param string $relationName name of active relarion to clone
* @param string $relationQuery additional join query for relation
* @throws \CException
*/
public function cloneRelation($originModel, $relationName, $relationQuery = null)
{
if (!isset($originModel[$relationName])) {
throw new \CException('Model ' . get_class($originModel) . ' has no relation ' . $relationName);
}
if ($relationQuery) {
$relatedRecords = $originModel->$relationName($relationQuery);
} else {
$relatedRecords = $originModel->$relationName;
}
if (count($relatedRecords) > 0) {
foreach ($relatedRecords as $key => $record) {
/** @var $record static */
$this->addRelatedRecord($relationName, $record->cloneModel(), true);
}
}
}
}
<?php
$newPost = $oldPost->cloneModel();
$newPost->cloneRelation($oldPost, 'comments');
@iJackUA
Copy link
Author

iJackUA commented Jul 22, 2016

Trait ActiveRecordClone should be included in all AR models: for Post model and Comment model

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment