Created
February 7, 2014 02:07
-
-
Save smithmilner/8856304 to your computer and use it in GitHub Desktop.
Example of a ManyToMany Relationship in Doctrine.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** @Entity */ | |
class User | |
{ | |
/** @Id @GeneratedValue @Column(type="string") */ | |
private $id; | |
/** | |
* Bidirectional - Many users have Many favorite comments (OWNING SIDE) | |
* | |
* @ManyToMany(targetEntity="Comment", inversedBy="userFavorites") | |
*/ | |
private $favorites; | |
public function getFavoriteComments() { | |
return $this->favorites->toArray(); | |
} | |
public function addFavorite(Comment $comment) { | |
$this->favorites->add($comment); | |
$comment->addUserFavorite($this); | |
} | |
public function removeFavorite(Comment $comment) { | |
$this->favorites->removeElement($comment); | |
$comment->removeUserFavorite($this); | |
} | |
} | |
/** @Entity */ | |
class Comment | |
{ | |
/** @Id @GeneratedValue @Column(type="string") */ | |
private $id; | |
/** | |
* Bidirectional - Many comments are favorited by many users (INVERSE SIDE) | |
* | |
* @ManyToMany(targetEntity="User", mappedBy="favorites") | |
*/ | |
private $userFavorites; | |
public function getUserFavorites() { | |
return $this->userFavorites->toArray(); | |
} | |
public function addUserFavorite(User $user) { | |
$this->userFavorites[] = $user; | |
} | |
public function removeUserFavorite(User $user) { | |
$this->userFavorites->removeElement($user); | |
} | |
} | |
/* | |
You will notice that addUserFavorite and removeUserFavorite do not call | |
addFavorite and removeFavorite, thus the bidirectional association is | |
strictly-speaking still incomplete. However if you would naively add the | |
addFavorite in addUserFavorite, you end up with an infinite loop, so more work | |
is needed. As you can see, proper bidirectional association management in plain | |
OOP is a non-trivial task and encapsulating all the details inside the classes | |
can be challenging. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment