Skip to content

Instantly share code, notes, and snippets.

@iJackUA
Last active March 24, 2019 10:43
Show Gist options
  • Select an option

  • Save iJackUA/6636ac60b763fdc1d14560e8900f8789 to your computer and use it in GitHub Desktop.

Select an option

Save iJackUA/6636ac60b763fdc1d14560e8900f8789 to your computer and use it in GitHub Desktop.

Revisions

  1. iJackUA renamed this gist Jul 22, 2016. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. iJackUA revised this gist Jul 22, 2016. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions Usage example
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,3 @@
    <?php
    $newPost = $oldPost->cloneModel();
    $newPost->cloneRelation($oldPost, 'comments');
  3. iJackUA created this gist Jul 22, 2016.
    50 changes: 50 additions & 0 deletions ActiveRecordClone.php
    Original 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);
    }
    }
    }
    }