【问题标题】:Get Taggables by common tags using rtconner/laravel-tagging使用 rtconner/laravel-tagging 通过常用标签获取 Taggables
【发布时间】:2014-10-04 08:15:29
【问题描述】:

我对 Laravel 很陌生。我安装了 RConner 的 Laravel-Tagging 插件。它工作正常。

在帖子页面上,我想获取具有相似标签的其他帖子(可标记)。 我知道我可以使用 sql 连接和计数来做到这一点(但不是真的如何)

我尝试向 TaggableTrait 添加范围方法,但我在连接方面遇到了困难。 我想知道是否有一种“Laravel 的方式”来施展魔法。

谢谢!

编辑: 实际上,我想要实现的是检索“可标记”,按当前内容的常见标签数量排序。

我正在尝试向 TaggableTrait 添加范围方法,例如:

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',closure) 但显然,它没有加入“标记”表...

$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');
});

这有点超出我的想象。有什么线索吗?

【问题讨论】:

    标签: php laravel laravel-4 tags


    【解决方案1】:

    如果你的关系正确,你也可以使用 Eloquent 来做。

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

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

    2- 然后您可以使用 eloquent 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();
    

    阅读此Querying Relations

    更新

    我刚刚查看了这个包,它有一个预定义的方法来获取类似的文章,这也和上面提到的一样。

    阅读包的docs

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

    【讨论】:

    • 我编辑了我的问题以更具体地说明我的需求,但你让我更进一步。感谢您的回复和文档链接。
    猜你喜欢
    • 2010-12-19
    • 1970-01-01
    • 2011-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 2019-01-28
    • 2021-03-27
    相关资源
    最近更新 更多