symfony2 一对多,双向
例子
这种双向映射需要mappedBy的属性,OneToMany协会和inversedBy该属性ManyToOne关联。
双向关系既有拥有的一面,也有相反的一面。OneToMany关系可以使用连接表,因此您必须指定拥有方。该OneToMany协会始终是一个双向关联的另一方。
username = $username; $this->group = $group; } /** * Set username * * @param string $username */ public function setUsername($username) { $this->username = $username; } /** * Get username * * @return string */ public function getUsername() { return $this->username; } /** * @param Group|null $group */ public function setGroup(Group $group = null) { if($this->group !== null) { $this->group->removeUser($this); } if ($group !== null) { $group->addUser($this); } $this->group = $group; } /** * Get group * * @return Group|null */ public function getGroup() { return $this->group; } }
name = $name; $this->users = new ArrayCollection(); } /** * @return string */ public function getName() { return $this->name; } /** * @param string $name */ public function setName($name) { $this->name = $name; } public function addUser(User $user) { if (!$this->getUsers()->contains($user)) { $this->getUsers()->add($user); } } public function removeUser(User $user) { if ($this->getUsers()->contains($user)) { $this->getUsers()->removeElement($user); } } public function getUsers() { return $this->users; } public function __toString() { return (string) $this->getName(); } }