2017-01-05 39 views
1

名爲Tags的MySQL表包含2列:具有超過100k行的tags和video_id。 他們都不是主鍵,這意味着在標籤列中的值可能與不同VIDEO_ID發生幾次,例如:計算行發生次數並將它們打印

column names: |tags|video_id| 
values:   tag1 video1 
       tag1 video2 
       tag2 video4 
       tag2 video5 
       tag2 video6 

我怎麼能指望每個標籤的所有事件和打印?喜歡的東西:

TAG1(2個視頻)

標籤2(3個視頻)

我的網站是基於CakePHP的-3,我的方式從表中獲得行就是這樣:

$query = $this->Tags->find('all'); 
$tags = $this->paginate($query); 

變量標籤現在有結果,這就是我如何打印出來:

foreach ($tags as $tag): 
     echo $tag->tags."<br>"; 
endforeach; 
+0

得到結果,你可以用一個標籤創建一個數組」關鍵「 –

+1

請永遠記住離開您的確切CakePHP版本(x.x.x),並相應地標記您的問題 - 謝謝! – ndm

+0

http://stackoverflow.com/questions/32584003/cakephp-3-count-group-find-result的可能重複 –

回答

3

您可以通過利用基本SQL邏輯來實現這一點,例如計數video_id(或*,這可能會在某些情況下提供更好的性能),並且可以通過tags進行分組。

$query = $this->Tags->find(); 
$query = $query 
    ->select([ 
     'tags', 
     'count' => $query->func()->count('video_id') 
    ]) 
    ->group('tags'); 

$tags = $this->paginate($query); 

這將創建一個類似的查詢:

SELECT tags, COUNT(video_id) as count 
FROM tags 
GROUP BY tags 

所得實體將舉行count屬性,您可以訪問像任何其他財產。這裏有一個小例子,還使用多個意識到翻譯功能(當然不是必需的,但可能是有用的):

foreach ($tags as $tag): 
    echo $tag->tags . ' (' . 
     __n('{0} Video', '{0} Videos', $tag->count, $tag->count) . 
    ')<br>'; 
endforeach; 

參見

2

您可以使用CakePHP count()功能和Group選項

$query = $this->Tags->find('all'); 
$tags = $query->select([ 
       'tags', 
       'count' => $query->func()->count('*') 
      ]) 
    ->group('tags'); 

您可以通過

foreach ($tags as $tag): 
     echo $tag->tags."(".$tag->count." Videos)"; 
endforeach; 
+0

您在標記之前錯過了$。 –

+0

@ManoharKhadka更新,謝謝 – tarikul05

相關問題