CakePHP 不会按条件应用分组


CakePHP Won't Apply Group By Condition

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

$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数组中-什么都没有。 我试过在组周围放一个数组 - 什么都没有。 我真的很难,所以如果有人能提供帮助,我将不胜感激。

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

它可以这样写(假设项目有很多项目时间):

$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')
        )
    )
));

(在编辑器中键入,未经测试;-)

我知道

这个答案很晚,但我修改了核心以允许在hasMany中分组。我不确定为什么 CakePHP 团队决定这样做,如果有人能提供他们为什么这样做的见解,我将不胜感激。

行:1730 的/lib/Cake/Model/Datasource/dboSource.php

        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'],
            );

值 $assocData['group'] 已添加到组键中。