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

两盒软妹~` 提交于 2019-12-04 04:22:43

问题


I've been looking far and wide and still haven't been able to find an example of how to setup a query to look for a specific 'tag' that the user selects from a sidebar which in turn will bring up all posts with that tag.

I understand how to find all tags, but not to find a specific selected by the user.

blogrepository

public function getTags($tags)
{
    $qb = $this->createQueryBuilder('b');
    $qb->select('b')
        ->join('b.tags', 'tag')
        ->where('b.tags LIKE ?', '%'.$tags.'%');

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

blog entity

/**
 * @var string
 *
 * @ORM\Column(name="tags", type="text")
 */
private $tags;

/**
 * Set tags
 *
 * @param string $tags
 * @return Blog
 */
public function setTags($tags)
{
    $this->tags = $tags;

    return $this;
}

/**
 * Get tags
 *
 * @return string
 */
public function getTags()
{
    return $this->tags;
}

回答1:


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();
    }



回答2:


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;
}


来源:https://stackoverflow.com/questions/23178723/symfony2-need-help-setting-up-a-doctrine-query-for-finding-tags

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