Symfony ManyToMany单向级联持续不起作用

时间:2017-12-01 13:41:39

标签: symfony doctrine-orm persist

使用symfony 3.3我有实体用户作为billingAddresses与ManyToMany单向关系:

实体\用户

class User extends EntitySuperclass implements AdvancedUserInterface, \Serializable 
{
/**
     * @ORM\ManyToMany(targetEntity="Address", cascade={"persist"})
     * @ORM\JoinTable(name="User_BillingAddress",
     *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="billing_address_id", referencedColumnName="id")}
     * )
     * @Assert\Count(
     *      min = 1,
     *      minMessage = "user.billing_addresses.min",
     * )
     * @Assert\Valid
     */
    private $billingAddresses;

/**
     * Add billingAddress
     *
     * @param \AppBundle\Entity\Address $billingAddress
     *
     * @return User
     */
    public function addBillingAddress(\AppBundle\Entity\Address $billingAddress)
    {
        $this->billingAddresses[] = $billingAddress;

        return $this;
    }

    /**
     * Remove billingAddress
     *
     * @param \AppBundle\Entity\Address $billingAddress
     */
    public function removeBillingAddress(\AppBundle\Entity\Address $billingAddress)
    {
        $this->billingAddresses->removeElement($billingAddress);
    }

    /**
     * Get billingAddresses
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getBillingAddresses()
    {
        return $this->billingAddresses;
    }
}

虽然我添加了cascade={"persist"},但" billingAddresses"当我持久保存实体用户时,不会保留/保存。我也尝试过双向关系,但地址仍然不存在。

2 个答案:

答案 0 :(得分:0)

您必须明确地执行以下操作

$user->addBillingAddress($address);

在调用persist并刷新

之前,请检查您是否正在执行上述操作
$em->persist($user);
$em->flush();

您必须手动建立实体之间的关联。它在文档中描述

http://docs.doctrine-project.org/en/latest/reference/working-with-associations.html#working-with-associations

谢谢!

答案 1 :(得分:0)

尝试将构造函数添加到User类

gzip
相关问题