CakePhp,在Containable中获得许多行的总数

时间:2010-09-02 17:11:40

标签: mysql database cakephp

我有一个查询,使用cakephp中的Containable行为,如下所示:

    $x = $this->find('first',array('contain'=>array(
    'User' => array(
        'SelectionsTeam' => array('conditions' => $conditionTeamSelection,
            'Team' => array(
                        'fields' => array('name','city','id'),
                            'TeamsStat' => $condition,
                                            ),
            'PointsHistory' => array('fields' => array('points'))
                                    ),

    ),
   'conditions' => array('id'=>$id)
));

Everythings运行良好但PointsHistory表返回我,例如10行,1个字段(点)。如何直接在可包含的中获取每行10行的SUM。因为现在,我需要做一个foreach并得到每个PointsHistory行的总和,我认为这是可以避免的。

在决赛中,我希望表格如下:[PointsHistory] => [Total] => 10

而不是:

[PointsHistory] => 
             [0] => 
                    ['points']
                           => 2 
             [1] => 
                    ['points'] 
                           => 1 
             [2] => 
                    ['points'] 
                           => 3

1 个答案:

答案 0 :(得分:2)

我认为不可能完全得到

[PointsHistory] => [Total] => 10

但我相信你所寻找的是:

    $x = $this->find('first',array('contain'=>array(
    'User' => array(
        'SelectionsTeam' => array('conditions' => $conditionTeamSelection,
            'Team' => array(
                        'fields' => array('name','city','id'),
                            'TeamsStat' => $condition,
                                            ),
            'PointsHistory' => array('fields' => array('SUM(points) total_points'))
                                    ),

    ),
   'conditions' => array('id'=>$id)
));

结果如下:

[PointsHistory] => [0] => [Total] => 10

我还没有测试过,所以将调试级别更改为2并查看它生成的代码:)