我对Laravel很新颖。我安装了RConner的Laravel-Tagging插件。它工作正常。使用rtconner/laravel标签获取标签的常用标签
在帖子页面上,我想获得其他帖子(标签)具有相似的标签。 我知道我可以做到这一点使用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');
});
这有点凌驾于我的头上。任何线索?
我编辑我的问题是更具体的了解我的需求的docs,但你让我又进了一步。感谢您的回复以及文档链接。 – 2014-10-04 11:37:44