ManyToMany自引用关系 - 如何优化此代码?

时间:2012-05-02 16:00:50

标签: php optimization orm symfony doctrine-orm

如何优化此代码。我发现更新相关文档的唯一方法是删除所有旧关系并设置新关系。这使得对未发生变化的关系进行了许多无用的删除/插入查询

控制器操作:

    foreach ($entity->getRelatedDocuments() as $document) {
        $oldRDs[] = $document;
    }
    if ($editForm->isValid()) {
        // filter $originalTags to contain tags no longer present
        $newRDs = $entity->getRelatedDocuments();

        // assign old and new relations
        if (!isset($oldRDs)) {
            $addRDs = $newRDs;
        } else {
            $delRDs = $oldRDs;
            $addRDs = $newRDs;
        } 
        // if there are old one remove them
        if (isset($delRDs)) {
            foreach ($delRDs as $document) {
                $document->removeDocument($entity);
            }
        }
        // if there are new one store them
        if (isset($addRDs)) {
            foreach ($addRDs as $document) {
                $document->addDocument($entity);
            }
        }       

        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('document_edit', array('id' => $id)));
    }

实体类:

/**
 * @var string $relatedDocuments
 *
 * @ORM\ManyToMany(targetEntity="Document")
 * @ORM\JoinTable(name="nb_link_documents_documents",
 *               joinColumns={@ORM\JoinColumn(name="document1_id", referencedColumnName="id")},
 *               inverseJoinColumns={@ORM\JoinColumn(name="document2_id", referencedColumnName="id")})
 */
private $relatedDocuments;

public function __construct()
{
    $this->relatedDocuments = new \Doctrine\Common\Collections\ArrayCollection();
}

public function addDocument(\NF\FundBundle\Entity\Document $relatedDocuments)
{
    $this->relatedDocuments[] = $relatedDocuments;
}

public function removeDocument(\NF\FundBundle\Entity\Document $relatedDocuments)
{
    foreach ($this->relatedDocuments as $key => $document) {
        if ($document->getId() == $relatedDocuments->getId())
            unset ($this->relatedDocuments[$key]);
    }
}

0 个答案:

没有答案