Last active
March 24, 2019 10:43
-
-
Save iJackUA/6636ac60b763fdc1d14560e8900f8789 to your computer and use it in GitHub Desktop.
Revisions
-
iJackUA renamed this gist
Jul 22, 2016 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
iJackUA revised this gist
Jul 22, 2016 . 1 changed file with 3 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,3 @@ <?php $newPost = $oldPost->cloneModel(); $newPost->cloneRelation($oldPost, 'comments'); -
iJackUA created this gist
Jul 22, 2016 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,50 @@ <?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); } } } }