Symfony2 - Need help setting up a doctrine query for finding tags

妖精的绣舞 提交于 2019-12-01 21:02:41

I believe this will work for you.

public function getPostsByTags($tag)
    {
        $query = $this->createQueryBuilder('b')
            ->where('b.tags like :tag')
            ->setParameter('tag', '%'.$tag.'%');

        return $query->getQuery()->getResult();
    }

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!