Last active
August 29, 2015 13:56
-
-
Save smithmilner/8856116 to your computer and use it in GitHub Desktop.
Example of a OneToMany 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 - One-To-Many (INVERSE SIDE) | |
* | |
* @OneToMany(targetEntity="Comment", mappedBy="author") | |
*/ | |
private $commentsAuthored; | |
public function getCommentsAuthored() { | |
return $this->commentsAuthored->toArray(); | |
} | |
public function setCommentsAuthored($comments) { | |
$this->commentsAuthored->clear(); | |
foreach ($comments as $comment) { | |
$this->addComment($comment); | |
} | |
return $this; | |
} | |
public function addComment(Comment $comment) { | |
// other events listening to the adding of a comment go here. | |
$this->commentsAuthored[] = $comment; | |
$comment->setAuthor($this); | |
return $this; | |
} | |
public function removeComment(Comment $comment) { | |
if ($this->commentsAuthored->removeElement($comment)) { | |
$comment->setAuthor(null); | |
} | |
} | |
} | |
/** @Entity */ | |
class Comment | |
{ | |
/** @Id @GeneratedValue @Column(type="string") */ | |
private $id; | |
/** | |
* Bidirectional - Many Comments are authored by one user (OWNING SIDE) | |
* | |
* @ManyToOne(targetEntity="User", inversedBy="commentsAuthored") | |
*/ | |
private $author; | |
public function setAuthor(User $author = null) { | |
$this->author = $author; | |
return $this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment