1st solution : You should use a doctrine query.
PostRepository.php
public function findByTagName($tagName)
{
$qb = $this->createQueryBuilder('post');
$qb->select('post')
->join('post.tags', 'tag')
->where('tag.name LIKE ?', '%'.$tagName.'%');
return $qb->getQuery()->getResult();
}
2nd solution : Use Many To Many relation and get directly from doctrine
Entity/Tag.php
/**
* @ORM\ManyToMany(targetEntity="YourApp\YourBundle\Entity\Post", inversedBy="tags")
* @ORM\JoinColumn(name="posts_tags")
*/
private $posts;
Entity/Post.php
/**
* @ORM\ManyToMany(targetEntity="YourApp\YourBundle\Entity\Tag", mappedBy="posts")
*/
private $tags;
So you can do $tag->getPosts();
to get all relative posts
3rd solution : Really ugly, but the tutorial is not designed to be improved ...
Get all blog post and parsing each string to find if your tag is in.
public function getBlogWithTag($tagRequested)
{
$blogs = $this->createQueryBuilder('b')
->getQuery()
->getResult();
$blogsWithTag = array();
$tags = array();
foreach ($blogs as $blog)
{
$tags = explode(",", $blog->getTags());
foreach ($tags as &$tag)
{
$tag = trim($tag);
}
if(in_array($tagRequested, $tags)) {
array_push($blogsWithTag, $blog);
}
}
return $blogsWithTag;
}