Search code examples
phpormdoctrinesymfony1symfony-1.4

Copy a Doctrine object with all relations


I want to copy a record with all his relations.

I'm trying with:

$o = Doctrine::getTable('Table')->Find(x); 
$copy = $object->copy();
$relations = $o->getRelations();

foreach ($relations as $name => $relation) {
  $copy->$relation = $object->$relation->copy();
} 

$copy->save();

This code doesn't works, but I think it's on the way.


Solution

  • I never could get the deep copy function to operate correctly.

    I manually coded a deep copy function for one of my models like this

    public function copyAndSave ()
    {
        $filters = array('id', 'created');
    
        $survey = $this->copy();
    
        $survey->Survey_Entries = new Doctrine_Collection("Survey_Model_Entry");
        $survey->Assignment_Assignments = new Doctrine_Collection("Assignment_Model_Assignment");
        $survey->Survey_Questions = new Doctrine_Collection("Survey_Model_Question");
    
        $survey->save();
    
        foreach ($this->Survey_Questions as $question)
        {
            $answers = $question->Survey_Answers;
            $newQuestion = $question->copy();
            $newQuestion->survey_surveys_id = $survey->id;
            $newQuestion->save();
            $newAnswers = new Doctrine_Collection("Survey_Model_Answer");
    
            foreach($answers as $answer)
            {
                $answer = $answer->copy();
                $answer->save();
                $answer->survey_questions_id = $newQuestion->id;
                $newAnswers->add($answer);
            }
            $newQuestion->Survey_Answers = $newAnswers;
    
            $survey->Survey_Questions->add($newQuestion);
        }
        return $survey->save();
    }