Skip to content

Instantly share code, notes, and snippets.

@anyt
Created January 9, 2014 23:58
Show Gist options
  • Save anyt/8344450 to your computer and use it in GitHub Desktop.
Save anyt/8344450 to your computer and use it in GitHub Desktop.
Count of Tags for Post in doctrine2 orm
<?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);
}
// ...
}
<?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