2014-02-11 51 views
0

我有多個查詢在foreach我知道它錯了,我要糾正它,我有virtual_fields這樣的:CakePHP的,變化的查詢來獲取所有在一個

'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,我想加入usershours,但我得到錯誤列night_hours不存在,做y你知道任何方法嗎?

這裏查詢之一:

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' 
+0

請發佈不起作用的代碼。另外,你嘗試包容嗎? – arilia

+0

你的意思是像'hasMany'等? – Viszman

+0

你提到你嘗試了一個獨特的連接查詢,但你有錯誤。發佈該代碼 – arilia

回答

0

你不必thiese列'night_hours', 'half_hours',在您的查詢,你給它不同的別名

試試這個

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

你AVE別名一樣,在您的查詢中

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 
      ...... 
      ...... 
相關問題