【问题标题】:Symfony OneToMany - ManyToOne entity association not workingSymfony OneToMany - ManyToOne 实体关联不起作用
【发布时间】:2016-10-18 18:38:20
【问题描述】:

我正在使用 Symfony 进行自我训练,并正在努力解决双向关联问题(非常基础),因为通过 dump 我的实体在树枝模板中,我验证了数据是否正确,但关联始终为空.

我的问题类似于this one,但没有共享解决方案。

我阅读了here 的文档,似乎我遵循了正确的步骤。

我的数据库包含一个 Parent 表和一个由 children.parent_id 作为外键相关的 Children 表,这两个表都已填充,我使用教义:生成:实体和教义:生成:CRUD。

在父母课上我有:

function __construct() {
  $this->lastUpd = new \DateTime();
  $this->children = new ArrayCollection();
}
/*
    * @ORM\OneToMany(targetEntity="AppBundle\Entity\Children", mappedBy="parent_id", cascade={"persist"})    
    */
    private $children;
    public function setChildren(ArrayCollection $children) {
        return $this->children = $children;
    }
    public function getChildren() {
        return $this->children;
    }

在儿童班我有:

/**
     * @var \AppBundle\Entity\Parents
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Parents", inversedBy="children")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="parent_id", referencedColumnName="parent_id")
     * })
     */
    private $parent_id;
    /**
     * Set parent_id
     * @param \AppBundle\Entity\Parents $parent_id
     * @return Parents
     */
    public function setParentID(\AppBundle\Entity\Parents $parent_id= null) {
        $this->parent_id = $parent_id;
        return $this;
    }
    /**
     * Get parent_id
     * @return \AppBundle\Entity\Parents
     */
    public function getParentID() {
        return $this->parent_id;
    }

作为查看 Simfony profiler (of parents list page) -> Doctrine -> Entities Mapping 我发现的附加信息(没有错误) AppBundle\Entity\Parents 和 AppBundle\Entity\Type (一个有效的单向 OneToMany 关联)。

很抱歉发布一个如此基本的错误,我敢打赌解决方案很简单,但我看不到它。

【问题讨论】:

    标签: symfony doctrine-orm


    【解决方案1】:

    注意:我假设您没有创建孩子的 ArrayCollection 并添加它们。

    你没有任何addChild 方法(你需要调用它)。

    ArrayCollection 很容易。

    public function addChild(Children $child) {
        $this->children->add($child);
    
    }
    

    您也可以使用removeChild

    public function removeChild(Children $child) {
        $this->children->removeElement($child);
    }
    

    然后在你的控制器中。

    $child = new Children();
    $parent->addChild($child);
    

    那么当你持久化父对象时,由于级联持久化,子对象将跟随。我也会添加cascade={"remove"},所以当你删除父级时,子级会去。

    【讨论】:

    • 你对我的建议很有用,我正在努力,但我期望的是 Parent 实体有一个相关的 Children 实体列表已经 fill 。从列出子实体的页面中,我可以转储正确相关的父实体。当我添加一个新的 Childern 时,我传递给一个 default Parent 并且它正确地 persisted 到数据库。所以我仍然缺少一些东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多