Skip to content

Instantly share code, notes, and snippets.

@smithmilner
Last active August 29, 2015 13:56
Show Gist options
  • Save smithmilner/8856116 to your computer and use it in GitHub Desktop.
Save smithmilner/8856116 to your computer and use it in GitHub Desktop.
Example of a OneToMany Relationship in Doctrine.
<?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