Associated entity not merged correctly

不想你离开。 提交于 2019-12-11 13:58:18

问题


I have 2 associated entities like this:

class Solicitation {
    <some fields>
    /**
     * @var \User
     *
     * @ORM\ManyToOne(targetEntity="User", fetch="EAGER", inversedBy="solicitation")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_user", referencedColumnName="id_user", nullable=false)
     * })
     * @OrderBy({"nome" = "ASC"})
     */
    private $user;
    <more fields>
}

I don't want to cascade operations. The problem is when I try to merge an existing User before persisting Solicitation, like this:

$em = $this->getDoctrine()->getManager();
if (!(\Doctrine\ORM\UnitOfWork::STATE_MANAGED === $em->getUnitOfWork()->getEntityState($solicitation->getUser()))) {
    $em->merge($solicitation->getUser());
}
$em->persist($solicitation);

...it won't change User UnitOfWork state to "MANAGED". I`ts still "DETACHED" and I receive and error on saving.


回答1:


It took me a whole day to find that

$em->merge($solicitation->getUser()) 

doesn't change the original entity, it returns a menaged entity. So the correct is:

$solicitation->setUser($em->merge($solicitation->getUser()));

then persist solicitation. Made this question in case someone else needs this.



来源:https://stackoverflow.com/questions/27321682/associated-entity-not-merged-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!