Last active
March 24, 2019 10:43
-
-
Save iJackUA/6636ac60b763fdc1d14560e8900f8789 to your computer and use it in GitHub Desktop.
Yii 1. Clone AR model and Relations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$newPost = $oldPost->cloneModel(); | |
$newPost->cloneRelation($oldPost, 'comments'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Trait
ActiveRecordClone
should be included in all AR models: for Post model and Comment model