2016-11-24 18 views
0

我怎樣才能針對該學說保存此關係的孩子做二傳手:setter方法symfony的實體變量

/** 
* @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

'children'是由'CollectionType'形式處理的嗎?如果是,檢查其''by_reference''選項http://symfony.com/doc/current/reference/forms/types/collection.html#by-reference – yceruto

+0

另外'setChildren()'不應該是'addChildren( )'而不是? – yceruto

+0

Yonel,是兒童CollectionType,by_reference添加false,並添加到用戶實體addChild,removeChild和所有的okey;)謝謝 –

回答

1
//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; 
} 
+0

這不是一個setter,而是一個加法器。取決於用例。 –

相關問題