2

以下查询返回一个包含正确 id 的数组,但所有值都为 null。

如果我删除聚合函数AVG()find('all')先做'list')。

$progress = $this->Trial->find('list', array(
    'fields' => array(
        'Trial.session_id',
        'AVG(Trial.first_reaction_time_since_probe_shown) AS average_reaction_time'
    ),
    'group' => 'Trial.session_id',
    'conditions' => array(
        'Trial.first_valid_response = Trial.probe_on_top',
        'TrainingSession.user_id IS NOT NULL'
    ),
    'contain' => array(
        'TrainingSession' => array(
            'conditions' => array(
                'TrainingSession.user_id' => $this->Auth->user('id') 
            )
        )
    ),
    'recursive' => 1,
));

当我通过 PhpMyAdmin 将生成的 SQL 查询发送到数据库时,它会返回我想要的结果。

SELECT 
    `Trial`.`session_id`, 
    AVG(`Trial`.`first_reaction_time_since_probe_shown`) AS average_reaction_time 
FROM 
    `zwang`.`trials` AS `Trial` 
LEFT JOIN 
    `zwang`.`training_sessions` AS `TrainingSession` ON (
        `Trial`.`session_id` = `TrainingSession`.`id` AND
        `TrainingSession`.`user_id` = 1
    )
WHERE 
    `Trial`.`first_valid_response` = `Trial`.`probe_on_top` 
GROUP BY 
    `Trial`.`session_id`

我检查了 find('list') 的来源。我认为这是由于在查询中使用函数时访问列表的“数组路径”搞砸了,但我还不能修复它(或者认识到我滥用 CakePHP 逻辑)。

4

1 回答 1

2

一旦我发布了这个问题,Stackoverflow 就开始将正确的答案与我联系起来。

显然,'list'没有virtualFields.
我没想到会这样,因为它可以使用其他查找类型。

$this->Trial->virtualFields = array(
    'average_reaction_time' => 'AVG(Trial.first_reaction_time_since_probe_shown)'
);
$progress = $this->Trial->find('list', array(
    'fields' => array('Trial.session_id','average_reaction_time')
    /* etc... */ 
));
于 2013-01-22T11:10:46.817 回答