CakePHP Group By字段每组只返回一个结果

时间:2012-11-22 14:42:20

标签: mysql cakephp group-by find

我有一张表如下:

id | date       | customer_id | env_id | jobs
1  | 2012-11-20 | 200         | 100    | 10
2  | 2012-11-20 | 200         | 101    | 15
3  | 2012-11-20 | 200         | 102    | 12
4  | 2012-11-21 | 200         | 100    | 10
5  | 2012-11-21 | 200         | 101    | 12
6  | 2012-11-21 | 200         | 102    | 20

我所追求的是按日期分组的结果。

$usage = $this->Environment->DailyCount->find('all',
array(
'conditions' =>array('DailyCount.customer_id' => $user['customer_id']),
'group' => array('DailyCount.date'),
'recursive'=>-1));

但它只返回一行我想要这三个!

结果:

Array
(
    [0] => Array
        (
            [DailyCount] => Array
                (
                    [id] => 1
                    [date] => 2012-11-20
                    [customer_id] => 200
                    [env_id] => 100
                    [jobs] => 10
                )
       )

    [1] => Array
        (
            [DailyCount] => Array
                (
                    [id] => 4
                    [date] => 2012-11-21
                    [customer_id] => 200
                    [env_id] => 100
                    [jobs] => 10
                )

        )
)

我的结果中的每个日期都是三行 - 我需要所有三个env_id工作计数。

任何人都可以帮助在CakePHP中如何做到这一点,甚至如何在MySQL中获得这样的结果,我可以找出蛋糕的方式!

----------- HACK SOLUTION ------------

我无法回答我自己的问题所以编辑问题

好的不是完美的解决方案,但为我工作,是一个快速的解决方案:

$dailyCount = $this->Environment->DailyCount->find('all',
array(
'conditions' => array('DailyCount.customer_id' => $user['customer_id']),
'order' => array('DailyCount.date DESC'),
'limit' => $limit,
'recursive'=>-1));

$usage = array();
foreach($dailyCount as $dc){
    $usage[$dc['DailyCount']['date']][] = $dc;
}

1 个答案:

答案 0 :(得分:0)

您可以使用MySQL的GROUP_CONCAT()。如果你正在分组,这可能是你最好的选择。