2014-10-04 189 views
1

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

這有點凌駕於我的頭上。任何線索?

回答

4

如果你的關係正確,你也可以使用雄辯。

我不知道你的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

更新

我只是看着它有一個預定義的方法來獲得類似的文章,其也在做同樣的事情上面提到的包。

閱讀包

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

我編輯我的問題是更具體的瞭解我的需求的docs,但你讓我又進了一步。感謝您的回覆以及文檔鏈接。 – 2014-10-04 11:37:44