来自包含记录的SUM字段

时间:2013-02-08 04:42:04

标签: cakephp group-by sum

在蛋糕2.1上,我需要从包含的记录中提取一个字段。

目前我得到子表上所有记录的总和,但需要按主表(员工)的ID进行分组。

出席属于员工

    $agents = $this->Employee->find('all', array(
        'fields' => array('Employee.FullNameNoId'),
        'conditions' => $conditions,
        'contain' => array(
            'Attend' => array(
                'conditions' => array(
                    'Attend.as_date BETWEEN ? AND ?' => array(
                        date('Y-m-d', strtotime($this->passedArgs['date1'])), 
                        date('Y-m-d', strtotime($this->passedArgs['date2']))
                    )
                ),
                'fields' => array('sum(Attend.as_labormin) AS total'),
                //'group' => array('Attend.employee_id') // This gets sql errors below
            )
        )
     ));

尝试了几种SQL错误组合:

'group' => array('Attend.employee.id') // Model "Attend" is not associated with model "Attend" 
                                      //Column not found: 1054 Unknown column                     
'group' => array('employee_id')        // Model "Attend" is not associated with model "employee_id"
                                      // Column not found: 1054 Unknown column 'Attend.group' in 'field list'

'group' => array('Employee.id')           //Column not found: 1054 Unknown column Attend.group' in 'field list'

表之间的关系很好,我可以获得相关记录,问题是按员工ID获得总和。

选中Cakephp SUM of related field,但使用SELECT SUM似乎很麻烦,而且他们遗漏了所需的分组。

你能帮忙吗?

1 个答案:

答案 0 :(得分:1)

尝试禁用'autoFields'。众所周知,使用聚合函数和“分组依据”语句会导致SQL错误。 Find out more here