复制具有所有关系的 Doctrine 对象

2022-01-16 00:00:00 orm php doctrine symfony1 symfony-1.4

我想复制他所有关系的记录.

I want to copy a record with all his relations.

我正在尝试:

$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.

推荐答案

我一直无法让深拷贝功能正常运行.

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

相关文章