CakePHP不会按条件应用Group

时间:2012-05-24 23:05:43

标签: php mysql cakephp group-by

我正在尝试在我的一个表上进行查找,并且我正在动态地将hasMany关系的条件从一个模型添加到另一个模型。一切正常,但Cake不会将组条件应用于查询。如果我复制生成的查询并在MySQL中运行它并添加我的Group By条件,它可以很好地工作。我已经尝试了很多东西,无济于事,我现在的方式设置就像Cake文档中的Find页面告诉我设置一个组。您可以在下面找到我的工作方式:

$this->Project->hasMany['ProjectTime']['conditions'] = array('user_id'=>$this->Auth->user('id'), 'date_entry >= '.$firstDay.' AND date_entry <= '.$lastDay);
    $this->Project->hasMany['ProjectTime']['order'] = array('date_entry ASC');
    $this->Project->hasMany['ProjectTime']['group'] = 'ProjectTime.date_entry';
    $this->Project->hasMany['ProjectTime']['fields'] = array('ProjectTime.date_entry, ProjectTime.user_id, ProjectTime.project_id, SUM(ProjectTime.duration) AS durationTotal');        
    $result = $this->Project->find('all', array('conditions'=>array('Project.id IN (' . implode(",", $projectTimeArray) . ')')));

我已经尝试将它直接放在模型中的hasMany数组中 - 没有。我试过在这个组周围放一个阵列 - 没什么。我真的很难过,所以如果有人能帮忙,我会非常感激。

2 个答案:

答案 0 :(得分:1)

这是构建查询的一种非常奇怪的方式:-S

可以这样写(假设Project hasMany ProjectTime):

$result = $this->Project->find('all', array(
    'conditions'=>array(
        'Project.id'=>implode(",", $projectTimeArray)
    ),
    'joins'=>array(
        array(
            'table'=>'project_times',
            'alias'=>'ProjectTime',
            'type'=>'INNER',
            'conditions'=>array(
                'ProjectTime.project_id = Project.id',
                'ProjectTime.user_id'=>$this->Auth->user('id'),
                'ProjectTime.date_entry >='=>$firstDay
                'ProjectTime.date_entry <=' => $lastDay
            ),
            'order'=>array('ProjectTime.date_entry'=>'ASC'),
            'group'=>array('ProjectTime.date_entry')
        )
    )
));

(输入编辑器,未经测试; - )

答案 1 :(得分:1)

我知道这个答案很晚,但我修改了核心以允许在hasMany中使用group。我不确定为什么CakePHP团队做出了这样做的决定,如果有人能够提供有关他们原因的见解,我将非常感激。

行:/lib/Cake/Model/Datasource/DboSource.php 1730

        case 'hasMany':
            $assocData['fields'] = $this->fields($LinkModel, $association, $assocData['fields']);
            if (!empty($assocData['foreignKey'])) {
                $assocData['fields'] = array_merge($assocData['fields'], $this->fields($LinkModel, $association, array("{$association}.{$assocData['foreignKey']}")));
            }

            $query = array(
                'conditions' => $this->_mergeConditions($this->getConstraint('hasMany', $Model, $LinkModel, $association, $assocData), $assocData['conditions']),
                'fields' => array_unique($assocData['fields']),
                'table' => $this->fullTableName($LinkModel),
                'alias' => $association,
                'order' => $assocData['order'],
                'limit' => $assocData['limit'],
                'offset' => $assocData['offset'],
                'group' => $assocData['group'],
            );

Value $ assocData [&#39; group&#39;]已添加到群组密钥中。