Search code examples
symfonytagsdoctrinetag-cloud

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


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

Solution

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