CakePHP计算ID在某个parrent内的所有项目

时间:2014-11-24 18:01:34

标签: php mysql cakephp

我有一个id,template_id和destination_id的数据库表。我想计算每个destination_id中的template_id的数量。所以我得到一个目的地中每个模板总数的数组。

在模型中我说了这个:

var $virtualFields = array(
    'template_count' => 'COUNT(Content.template_id)'
);

我确实得到了每个模板的计数。只有我不知道如何获得总计数

1 个答案:

答案 0 :(得分:1)

基于聚合函数在模型中定义虚拟字段。

我认为您需要的是一个看起来像的查询:

SELECT Content.destination_id, COUNT(Content.template_id) AS template_count
FROM contents AS CONTENT
GROUP BY Content.destination_id

尝试使用这个Cakephp代码:

$this->find('all' array(
  'fields' => array('Content.destination_id'
                  , 'COUNT(Content.template_id) AS template_count'),
  'group' => array('Content.destination_id')));
相关问题