Associated entity not merged correctly

2019-08-08 14:51发布

问题:

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.