无法将关系保存在自引用实体中

时间:2014-07-23 09:25:33

标签: symfony doctrine-orm fixtures self-reference

我想将通信部分添加到我的数据夹具中的rootCommunication,没有错误,但在数据库字段'root_communication_id'中只有NULL。为什么呢?

模型'沟通'的部分内容

/**
 * Communication
 *
 * @ORM\Table(name="communication")
 * @ORM\Entity(repositoryClass="Mother\BaseBundle\Entity\Repository\CommunicationRepository")
 */
class Communication
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="message", type="text", nullable=true)
     */
    private $message;

     /**
     * @ORM\ManyToOne(targetEntity="Communication", inversedBy="childrenCommunication", cascade={"persist"})
     * @ORM\JoinColumn(name="root_communication_id", referencedColumnName="id", nullable=true)
     * 
     */
    private $rootCommunication;

    /**
    * @ORM\OneToMany(targetEntity="Communication", mappedBy="rootCommunication")
    * 
    */
    private $childrenCommunication;

}

在第一个数据夹具中,我向数据库添加了三个通信,在这个secound夹具中,我将childrenCommunication添加到rootCommunication。

     /**
     * {@inheritDoc}
     */
    public function load( ObjectManager $manager ){

        $contentRepo = $this->container->get('doctrine')->getManager()->getRepository('MotherBaseBundle:Communication');


        $communication1 = $contentRepo->find( $this->getReference('communication1')->getId() );
        $communication1->addChildrenCommunication( $this->getReference('communication2') );
        $communication1->addChildrenCommunication( $this->getReference('communication3') );


        $manager->persist( $communication1 );
        $manager->flush();
}

1 个答案:

答案 0 :(得分:0)

我假设您在添加孩子时没有设置rootCommunication

您应该在add方法中添加自动设置器,例如..

public function addChildrenCommunication(CommunicationInterface $communication)
{
    if (!$this->childrenCommunication->contains($communication)) {
        $this->childrenCommunication->add($communication);
        $communication->setRootCommunication($this);
    }

    return $this;
}

..和删除相同..