Doctrine-在父级上调用setter时,“自动”删除子级集合元素

问题描述 投票:0回答:1

因此,在使用教义的应用程序中,我有实体Polls和PollAnswers。 PollAnswers链接到Polls as ManyToOne:

class PollAnswers
{
    /**
     * @var \Polls
     *
     * @ORM\ManyToOne(targetEntity="Polls", inversedBy="answers", fetch="LAZY")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="poll_id", referencedColumnName="id")
     * })
     */
    private $poll;

当我从UI添加/删除/更新民意测验答案时,我运行下一个代码:

    $answers = new ArrayCollection;
    foreach ($_POST['answers'] as $key => $answer)
    {
        $poll_answer = $em->getRepository(PollAnswers::class)->find($_POST['answers_ids'][$key]) ?: new PollAnswers;

        $poll_answer->setPoll($poll);
        $poll_answer->setAnswer($answer);

        $answers[]=$poll_answer;
    }

    $poll->setAnswers($answers);

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

但是,如果从UI中删除了投票答案,它将保留在数据库中。因此,此外,我还必须编写这样的“丑陋”代码:

    foreach ($poll->getAnswers() as $answer)
        if (!$answers->contains($answer))
            $em->remove($answer);

我能以某种方式避免添加此“丑陋”的片段吗?因此,当我执行setAnswers($ answers)时,Doctrine会自动查找已删除/丢失的实体并将其删除吗?我敢肯定,这样做有一种“优雅”的方式。

doctrine entity
1个回答
0
投票

在您的Poll实体中,将orphanRemoval=true设置为PollAnswers,如下所示:

* @ORM\OneToMany(targetEntity="PollAnswers", ... , orphanRemoval=true)

请参见文档here

© www.soinside.com 2019 - 2024. All rights reserved.