在查询CakePHP中计算数值

时间:2011-09-19 05:38:14

标签: cakephp cakephp-1.3

我尝试根据文档计算CakePHP中的数值。无论我尝试什么,我只收到该列的行数而不是数值的总和。

我的文章模型中的查询:

我尝试计算数据库中所有文章的hitcount数量。 hitcount是一个INT字段:

$total_articles = $this->find('count', array('fields' => 'Article.hitcount'));

//返回3,即数据库中的总行数

我尝试计算来自特定用户的hitcounts数量

$hitcountUser = $this->find('count', array('fields' => 'Article.hitcount', 'conditions' => array('Article.user_id' => $user)));

//返回3,数据库中的总行数,所有文章都由该用户发布。

如何总结Article.hitcount中的数值?我用Google搜索但找不到答案。

1 个答案:

答案 0 :(得分:0)

Count不会对要检索的字段中的值求和。它执行MySQL计数,计算结果中返回的行数。

为了对字段求和,您必须返回MySQL SUM值或循环遍历PHP中的结果并将它们相加。

我会这样做:

$article = $this->Model->find(
    'first',
    array(
        'fields'=>array('SUM('Article.hitcount') AS Article.hitcountsum'),
    )
);

哪个应该给你一个像:

这样的数组
$article['Article']['hitcountsum'];
相关问题