2012-07-02 50 views
0

我擴展了CakePHP博客教程,併爲我的文章添加了類別。帖子模型屬於類別模型。在我的帖子查看我的循環把我的分類表中列出類別在視圖,工作正常的菜單:CakePHP循環計數

/* gets the category names for the menu */ 
$this->set('category', $this->Post->Category->find('all')); 

現在我嘗試添加的職位數量,以每個菜單(類別)項目。到目前爲止,我得到了這個:

/* gets the category count for category 2*/ 
$this->set('category_2_count', $this->Post->find('count', array(
'conditions' => array('Category.id =' => '2')))); 

問題是,我顯然不能在我的視圖中使用循環了。有了這個我必須得到每個類別+每個計數,這似乎很不雅。有沒有辦法查詢類別名稱和計數,並獲得一個視圖的數組?

任何想法?我是新來的蛋糕和任何幫助,不勝感激。

回答

0

在你的控制器:

$this->set('category', $this->Post->Category->find('all', array(
    'fields' => array(
     '*', 
     '(SELECT COUNT(*) FROM posts WHERE category_id = Category.id) AS `post_count`' 
    ) 
))); 

在你看來:

foreach ($category as $c) { 
    echo $c['Category']['name']; // category name 
    echo $c[0]['post_count']; // post count 
} 
+0

非常感謝,作品像一個魅力:-) – Joshua

+0

不客氣! – Hoff

0

試試這個:

$stats = $this->Category->Post->find('all', array(
    'fields' => array(
     'Category.*', 
     'COUNT(Post.id) AS cnt' 
    ), 
    'group' => 'Category.id' 
)); 
+0

但我不能先訪問類型模型:「試圖獲得的財產非對象」。 – Joshua

+0

在上面加上這一行: 'Controller :: loadModel('Category');' – jagm