0

How I can to do setter for children that doctrine save relation for this:

/**
 * @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();
}

My setter, it dont' throw error and don't save relation:

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

Users doctrine save, relation not.

yceruto
  • 9,230
  • 5
  • 38
  • 65
  • 1
    `children` is handled by a `CollectionType` form? if yes, checks its `'by_reference'` option http://symfony.com/doc/current/reference/forms/types/collection.html#by-reference – yceruto Nov 24 '16 at 14:47
  • Also `setChildren()` shouldn't be `addChildren()` instead ? – yceruto Nov 24 '16 at 14:48
  • Yonel, yes children CollectionType, by_reference add false, and add to user entity addChild, removeChild and all okey ;) thanks –  Nov 24 '16 at 17:25

1 Answers1

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;
}
OlivierC
  • 682
  • 4
  • 11