Copy a Doctrine object with all relations

12,038

Solution 1

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();
}

Solution 2

You can read about copy() here. It takes an optional parameter $deep:

$deep
whether to duplicates the objects targeted by the relations

So

$copy = $object->copy(true);

should do it.

Solution 3

Sorry if I'm resurrecting this thread...

I found myself in search of a solution recently where I needed to copy a record and retain the references of the original. A deep copy $record->copy(true) copies the references, which was no good for me. This was my solution:

$record = Doctrine_Core::getTable('Foo')->find(1);
$copy = $record->copy();

foreach($record->getTable()->getRelations() as $relation) {
    if ($relation instanceof Doctrine_Relation_Association) {
        $ids = array();

        foreach ($relation->fetchRelatedFor($record) as $r) {    
            $ids[] = $r->getId();
        }

        $copy->link($relation->getAlias(), $ids);
    }
}

if ($copy->isValid()) {
    $copy->save();
}

Hope this helps :)

Share:
12,038
manolovn
Author by

manolovn

Updated on June 04, 2022

Comments

  • manolovn
    manolovn almost 2 years

    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.