【问题标题】:Symfony2 - Setting up a tag cloud in the side barSymfony2 - 在侧边栏中设置标签云
【发布时间】:2014-06-04 08:34:37
【问题描述】:

我正在寻找重新创建您通常在博客中看到的标签云侧边栏,用户在其中选择标签并显示具有该特定标签的所有帖子。

现在我无法确定如何设置查询。

我有查询拉出所有标签:

$blogTags = $this->createQueryBuilder('b')
        ->select('b.tags')
        ->getQuery()
        ->getResult();

    return $blogTags;

但是我如何将它设置为只提取用户从侧边栏中的一组标签中选择的标签的帖子?

我有存储标签并在侧边栏中加权它们的代码,我正在寻找将标签链接到其特定帖子的下一步。

getsTags()

public function getTags()
{
    $blogTags = $this->createQueryBuilder('b')
        ->select('b.tags')
        ->getQuery()
        ->getResult();

    $tags = array();

    foreach ($blogTags as $blogTag) {
        $tags = array_merge(explode(",", $blogTag['tags']), $tags);
    }

    foreach ($tags as $tag) {
        $tag = trim($tag);
    }

    return $tags;
}

getTagWeights()

public function getTagWeights($tags)
{
    $tagWeights = array();
    if (empty($tags))
        return $tagWeights;

    foreach ($tags as $tag)
    {
        $tagWeights[$tag] = (isset($tagWeights[$tag])) ? $tagWeights[$tag] + 1 : 1;
    }
    // Shuffle the tags
    uksort($tagWeights, function() {
        return rand() > rand();
    });

    $max = max($tagWeights);

    // Max of 5 weights
    $multiplier = ($max > 5) ? 5 / $max : 1;
    foreach ($tagWeights as &$tag)
    {
        $tag = ceil($tag * $multiplier);
    }

    return $tagWeights;
}

【问题讨论】:

  • 在标签表中存储一个计数器,然后您可以使用计数器按其受欢迎程度显示标签
  • 对,我知道了,但我正在寻找下一步,我在标签上选择它会显示相应的帖子。

标签: symfony tags doctrine posts


【解决方案1】:

和你朋友一样的答案 (Symfony2 - Need help setting up a doctrine query for finding tags)

您应该使用教义查询。

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

【讨论】:

    【解决方案2】:

    希望这可以帮助其他人在这方面花费数小时。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多