第一个解决方案:您应该使用学说查询。
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();
}
第二种解决方案:使用多对多关系并直接从学说中获取
实体/标签.php
/**
* @ORM\ManyToMany(targetEntity="YourApp\YourBundle\Entity\Post", inversedBy="tags")
* @ORM\JoinColumn(name="posts_tags")
*/
private $posts;
实体/Post.php
/**
* @ORM\ManyToMany(targetEntity="YourApp\YourBundle\Entity\Tag", mappedBy="posts")
*/
private $tags;
所以你可以做$tag->getPosts();
获取所有相关帖子
第三种解决方案:确实很难看,但教程并不是为了改进而设计的......
获取所有博客文章并解析每个字符串以查找您的标签是否在其中。
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;
}