【发布时间】: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