使用rtconner/lavel标记通过常见标记获取标记


Get Taggables by common tags using rtconner/laravel-tagging

我对Laravel很陌生。我安装了RConner的Laravel标签插件。它运行良好。

在一个帖子页面上,我想得到其他有类似标签的帖子。我知道我可以使用sql连接和计数(但不是真正的方法)

我试图向TagableTrait添加一个scope方法,但我在连接方面遇到了困难。我想知道是否有一种"拉拉威尔的魔法之路"。

谢谢!

编辑:实际上,我试图实现的是检索"taggables",按当前内容的常用标签数量排序。

我正在尝试向TagableTrait添加一个scope方法,例如:

public function scopeWithCommonTag($query, $tagNames)
{
    $tagNames = TaggingUtil::makeTagArray($tagNames);
    $normalizer = 'Config::get('tagging::normalizer');
    $normalizer = empty($normalizer) ? ''Conner'Tagging'TaggingUtil::slug' : $normalizer;
    $tagNames = array_map($normalizer, $tagNames);
    $query = $query->whereHas('tagged', function ($q) use ($tagNames) {
        $q->whereIn('tag_slug', $tagNames)->groupBy('taggable_id')->orderByRaw('count(*)');
    });
}

结果查询为:

select * from `contents` where (
    select count(*) from `tagging_tagged` 
    where `tagging_tagged`.`taggable_id` = `contents`.`id` 
    and `tagging_tagged`.`taggable_type` = ? 
    and `tag_slug` in (?, ?) 
    group by `taggable_id` 
    order by count(*)
) >= 1

我需要的是:

select * from `contents` where taggable_id in (
    select taggable_id,count(*) as common_tags 
    from `tagging_tagged` 
    where `tagging_tagged`.`taggable_id` = `contents`.`id` 
    and `tagging_tagged`.`taggable_type` = ? 
    and `tag_slug` in (?, ?) 
    group by `taggable_id` 
    order by common_tags desc
) limit 3;

也许是这样的(我试着使用whereIn('id',闭包),但很明显,它没有加入"标记"表。。。

$query = $query->whereHas('tagged', function ($q) use ($tagNames) {
    $q->select(array('taggable_id','DB::raw('count(*) as common_tags')))->whereIn('tag_slug', $tagNames)->groupBy('taggable_id')->orderByRaw('common_tags desc');
});

这有点让我不知所措。有线索吗?

如果关系正确,也可以使用Eloquent。

我不知道你的模式是什么,所以这个解决方案是一个通用的形式。

1-获取帖子的所有标签的id。

2-然后你可以使用雄辩的whereHas方法来查询你的关系。像这样的

$postTags = [1,2,3,4,5]; //  List of tags id of a particular post
$similarPosts = Post::whereHas('tags', function($q) use ($postTags) {
    $q->whereIn('id', $postTags);
})->get();

阅读此查询关系

更新

我只是看了一下这个包,它有一个预定义的方法来获得类似的文章,它也在做与上面提到的相同的事情。

阅读包装的文档

Article::withAnyTag(array('Gardening','Cooking'))->get();