Cakephp,更改查询以获取所有内容

时间:2014-02-11 09:40:12

标签: php mysql cakephp cakephp-2.0

我在foreach中有多个查询我知道错了,我想纠正它,我有virtual_fields这样:

'night_hours' => 'SUM(Hour.night)',
'half_hours' => 'SUM(Hour.half)',
'NN' => 'SUM(Hour.day_off_id = 13)'

我在控制器中的foreach循环:

foreach ($users as $user){
        $set_of_days = $this->Hour->find('all', array(
                'fields' => array('hour_from', 'hour_to', 'day_off_id', 'night_hours', 'half_hours', 'NN'),
                'conditions' => 
                    array('subordinate_id' => $user['User']['id'],
                          'date(Hour.date) BETWEEN ? AND ?' => array($date_from, $date_to))));

它的工作正常但是当我在一个视图中有4k用户它会杀死db时,我想用users加入表hours但我得到列night_hours的错误不存在,你们知道吗?

以下是查询之一:

SELECT `Hour`.`hour_from`, `Hour`.`hour_to`, `Hour`.`day_off_id`, (SUM(`Hour`.`night`)) AS `Hour__night_hours`, (SUM(`Hour`.`half`)) AS `Hour__half_hours`, (SUM(`Hour`.`day_off_id` = 13)) AS `Hour__NN` FROM `kadry`.`hours` AS `Hour` WHERE `subordinate_id` = 193 AND date(`Hour`.`date`) BETWEEN '2014-01-11' AND '2014-02-11'

1 个答案:

答案 0 :(得分:0)

您没有这些列'night_hours', 'half_hours',在您的查询中,您为其提供了不同的别名

试试这个

  'fields' => array('hour_from', 'hour_to', 'day_off_id', 'Hour__night_hours', 'Hour__half_hours', 'NN'),

你在查询中有这样的别名

 SELECT `Hour`.`hour_from`,
          `Hour`.`hour_to`, 
          `Hour`.`day_off_id`,
          (SUM(`Hour`.`night`)) AS `Hour__night_hours`,   
                                   ^^^^^^^^^^^^^^^^^^^//---> here your alias
          (SUM(`Hour`.`half`)) AS `Hour__half_hours`,   
                                  ^^^^^^^^^^^^^^^^^^   //---> here your alias
          ......
          ......