symfony实体中变量的setter

时间:2016-11-24 13:54:09

标签: symfony doctrine-orm entity

我如何为那些教导保存关系的孩子做一个setter:

/**
 * @ORM\ManyToMany(targetEntity="User", mappedBy="parents", cascade={"persist"})
 */
private $children;

/**
 * @ORM\ManyToMany(targetEntity="User", inversedBy="children")
 * @ORM\JoinTable(
 *     name="family",
 *     joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
 *     inverseJoinColumns={@ORM\JoinColumn(name="family_user_id", referencedColumnName="id")}
 * )
 */
private $parents;

/**
 * User constructor.
 */
public function __construct() 
{
    $this->children = new \Doctrine\Common\Collections\ArrayCollection();
    $this->parents = new \Doctrine\Common\Collections\ArrayCollection();
}

我的二传手,它不会抛出错误而不保存关系:

/**
 * @param mixed $children
 */
public function setChildren($children)
{
    $this->children[] = $children;
    $children->setParents($this);
}

用户原则保存,关系不是。

1 个答案:

答案 0 :(得分:0)

//Methods to add parents and Children
public function addChild(User $child)
{
    $this->children->add($child);

    $child->addParent($this);

    return $this;
}

public function addParent(User $parent)
{
    $this->parents->add($parent);

    return $this;
}


//Methods to remove parents and children
public function removeChild(User $child)
{
    $this->children->removeElement($child);

    $child->removeParent($this);

    return $this;
}

public function removeParent(User $parent)
{
    $this->parents->removeElement($parent);

    return $this;
}