Created
January 9, 2014 23:58
-
-
Save anyt/8344450 to your computer and use it in GitHub Desktop.
Count of Tags for Post in doctrine2 orm
This file contains 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 | |
namespace Anyt\BlogBundle\Entity; | |
use Doctrine\Common\Collections\ArrayCollection; | |
use Doctrine\ORM\Mapping as ORM; | |
/** | |
* Post | |
* | |
* @ORM\Table(name="posts") | |
* @ORM\Entity | |
*/ | |
class Article | |
{ | |
// ... | |
/** | |
* @ORM\ManyToMany(targetEntity="Tag", inversedBy="posts", orphanRemoval=true, cascade={"persist"}) | |
* @ORM\JoinTable(name="posts_tags") | |
* @ORM\OrderBy({"name" = "ASC"}) | |
*/ | |
private $tags; | |
// ... | |
/** | |
* Add tags | |
* | |
* @param \Anyt\BlogBundle\Entity\Tag $tag | |
* @return Post | |
*/ | |
public function addTag(\Anyt\BlogBundle\Entity\Tag $tag) | |
{ | |
$this->tags[] = $tag; | |
$tag->addPost($this); | |
return $this; | |
} | |
/** | |
* Remove tags | |
* | |
* @param \Anyt\BlogBundle\Entity\Tag $tags | |
*/ | |
public function removeTag(\Anyt\BlogBundle\Entity\Tag $tag) | |
{ | |
$this->tags->removeElement($tag); | |
$tag->removePost($this); | |
} | |
// ... | |
} |
This file contains 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 | |
namespace Anyt\BlogBundle\Entity; | |
use Doctrine\Common\Collections\ArrayCollection; | |
use Doctrine\ORM\Mapping as ORM; | |
/** | |
* Tag | |
* | |
* @ORM\Table(name="tags") | |
* @ORM\Entity | |
*/ | |
class Tag | |
{ | |
// ... | |
/** | |
* @var integer | |
* | |
* @ORM\Column(name="taggedPostsCount", type="integer") | |
*/ | |
private $taggedPostsCount = 0; | |
/** | |
* @ORM\ManyToMany(targetEntity="Post", mappedBy="tags") | |
**/ | |
private $posts; | |
// ... | |
/** | |
* Add posts | |
* | |
* @param \Anyt\BlogBundle\Entity\Post $post | |
* @return Tag | |
*/ | |
public function addPost(\Anyt\BlogBundle\Entity\Post $post) | |
{ | |
if (!$this->posts->contains($post)) { | |
$this->posts[] = $post; | |
$this->taggedPostsCount++; | |
} | |
return $this; | |
} | |
/** | |
* Remove posts | |
* | |
* @param \Anyt\BlogBundle\Entity\Post $post | |
*/ | |
public function removePost(\Anyt\BlogBundle\Entity\Post $post) | |
{ | |
if ($this->posts->removeElement($post)) { | |
$this->taggedPostsCount--; | |
} | |
} | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment