2017-06-19 107 views
0

我有一個網站的圖像,和圖像可以有標籤。許多圖像也可以具有相同的標籤。所以2張圖片可以有標籤「繪畫」。Laravel/SQL按人氣/趨勢排序

我有一個images表,一個tags表和一個images_tag數據透視表。

images_tag表具有列:idimages_idtag_idcreated_at

我想要的是能夠基本上找到哪些標籤趨勢,例如在過去的72小時內。

這意味着我想有一個查詢,發生在過去72小時

$trendingTags = ImagesTag::where('created_at', '>=', Carbon::now()->subHours(72)) 

使用的所有標籤和需要,比方說,前3名最常用的標籤。所以在這種情況下,

$trendingTags = ImagesTag::where('created_at', '>=', Carbon::now()->subHours(72)) 
->orderBy('tag_id most frequently used', 'desc') 
->take(3); 

我該怎麼做這項工作?

編輯:

針對FUBAR的回答,我試過如下:

控制器:

$trendingTags = Tag::selectRaw('tags.*, COUNT(image_tag.id) AS count') 
->join('image_tag', 'tags.id', '=', 'image_tag.tag_id') 
->where('created_at', '>=', Carbon::now()->subHours(72)) 
->orderBy('count', 'desc') 
->take(3); 

return view('home') 
>with('trendingTags', $trendingTags) 

這給我的錯誤:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'commendme.image_tag' doesn't exist (SQL: select count(*) as aggregate from tags inner join image_tag on tags . id = image_tag . tag_id where created_at >= 2017-06-16 02:44:02 order by count desc limit 3)

所以我嘗試切換代碼以反映images_ta摹表(而不是IMAGE_TAG,我猜是FUBAR的部分錯字),我得到了另一個錯誤:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'count' in 'order clause' (SQL: select count(*) as aggregate from tags inner join images_tag on tags . id = images_tag . tag_id where created_at >= 2017-06-16 02:45:15 order by count desc limit 3) (View: C:\xampp\htdocs\series\commend-me\CommendMe\resources\views\home.blade.php)

編輯2:嘗試FUBAR最後的編輯後

新的錯誤:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'image_count' in 'order clause' (SQL: select count(*) as aggregate from tags inner join images_tag on tags . id = images_tag . tag_id where created_at >= 2017-06-16 02:55:17 group by tags . id order by image_count desc limit 3) (View: C:\xampp\htdocs\series\commend-me\CommendMe\resources\views\home.blade.php)

回答

3

我從你的解釋猜你真正想要的Tag模型本身,而不是樞軸數據。

如果是這樣,那麼你就需要加入tags表到image_tag表,再算上imagestags表之間的關係數量。一旦你有這個價值,只需按順序。

$trendingTags = Tag::selectRaw('tags.*, COUNT(images_tag.id) AS image_count') 
    ->join('images_tag', 'tags.id', '=', 'images_tag.tag_id') 
    ->where('images_tag.created_at', '>=', Carbon::now()->subHours(72)) 
    ->groupBy('tags.id') 
    ->orderBy('image_count', 'desc') 
    ->take(3) 
    ->get(); 

編輯

針對張貼OP的錯誤。

我注意到我引用的連接表實際上被稱爲images_tag,而不是image_tag。 OP,命名數據透視表時,按字母順序使用關係的單數名稱是Laravel標準。然而,我修改了我的答案。

我還注意到我錯過了重要的groupBy聲明,這是SQL聚合器函數所要求的聲明。

最後,我已將count更名爲image_count,以防MySQL認爲這是保留字。

編輯#2

我只是在我的項目之一進行了測試,它的工作如預期。

$categories = FaqCategory::selectRaw('faq_categories.*, COUNT(faq_faq_category.id) AS faq_count') 
    ->join('faq_faq_category', 'faq_categories.id', '=', 'faq_faq_category.faq_category_id') 
    ->groupBy('faq_categories.id') 
    ->orderBy('faq_count', 'desc') 
    ->take(3) 
    ->get(); 
+0

感謝您的回答。不幸的是你的代碼給了我一些錯誤。我編輯了主帖以顯示這些錯誤。 –

+0

@FelixMaxime - 我已經更新了我的答案。 – fubar

+0

試過了。另一個錯誤。再次編輯主要帖子。 –