Symfony2 - Need help setting up a doctrine query f

2019-02-25 06:18发布

问题:

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