如何深度复制Yii 1.x模型

如何深度复制Yii 1.x模型,yii,model,copy,clone,relation,Yii,Model,Copy,Clone,Relation,我正在寻找一个简单的解决方案来深度复制Yii模型,包括所有关系(更新外国id和其他东西),但到目前为止还没有找到令人满意的东西 所以我想出了一个解决办法,想和你们讨论一下 我扩展了CActiveRecord并添加了此复制方法。你觉得怎么样 /** * @return BaseModel */ public function copy() { $newModel = new static(); $newModel->attributes = $this->attri

我正在寻找一个简单的解决方案来深度复制Yii模型,包括所有关系(更新外国id和其他东西),但到目前为止还没有找到令人满意的东西

所以我想出了一个解决办法,想和你们讨论一下

我扩展了CActiveRecord并添加了此复制方法。你觉得怎么样

/**
 * @return BaseModel
 */
public function copy() {
    $newModel = new static();
    $newModel->attributes = $this->attributes;
    $newModel->save();

    foreach ($this->relations() as $property => $relationDefinition) {
        list($type, $refModel, $refProperty) = $relationDefinition;

        if ($type == self::HAS_MANY) {
            foreach ($this->$property as $oldRefModel) {
                /** @var BaseModel $newRefModel */
                $newRefModel = $oldRefModel->copy();
                $newRefModel->$refProperty = $newModel->id;
                $newRefModel->save();
            }
        } else if ($type == self::HAS_ONE) {
            /** @var BaseModel $newRefModel */
            $newRefModel = $this->$property->copy();
            $newRefModel->$refProperty = $newModel->id;
            $newRefModel->save();
        }
    }

    return $newModel;
}

好。我还建议将克隆关系移动到新方法。我认为这应该通过定义
\uu clone()
方法并使用
clone
关键字复制对象来实现,因为这是PHP解决此问题的标准方法。好。我还建议将克隆关系移动到新方法。我认为这应该通过定义
\uu clone()
方法并使用
clone
关键字复制对象来实现,因为这是PHP解决此问题的标准方法。