2012-12-13 20 views
1

COUNT表達我有2個表:編寫SQL在Kohana中

事件(ID,incident_description) 評論(ID,incident_id,comment_description)

我想寫這樣的SQL表達式:

SELECT incident.*, COUNT(comment.id) AS com 
FROM incident 
LEFT JOIN comment ON comment.incident_id=incident.id 
GROUP BY incident.id 
ORDER BY com DESC 

它在phpmyadmin中正常工作。

我寫在ORM:

ORM::factory('incident') 
->select('incident.*',array('COUNT("comment.id")', 'com')) 
->join('comment', 'LEFT') 
->on('comment.incident_id', '=', 'incident.id') 
->group_by('incident.id') 
->order_by('com', 'DESC') 
->find_all(); 

但我得到一個錯誤: 系統/庫/ database.php中[296]: * 修剪()預計參數1是字符串,數組給定 *

從database.php中的代碼:

foreach ($sql as $val) 
       { 
         if (($val = trim($val)) === '') continue; 

         if (strpos($val, '(') === FALSE AND $val !== '*') 
         { 
           if (preg_match('/^DISTINCT\s++(.+)$/i', $val, $matches)) 
           { 
             $val   = $this->config['table_prefix'].$matches[1]; 
             $this->distinct = TRUE; 
           } 
           else 
           { 
             $val = (strpos($val, '.') !== FALSE) ? $this->config['table_prefix'].$val : $val; 
           } 

           $val = $this->driver->escape_column($val); 
         } 

         $this->select[] = $val; 
       } 
+0

什麼特殊字段'comment_count'爲'incident'表?您可以使用事件(評論添加/刪除)來增加它,而不是每次計數。 – biakaveron

回答

4

array(DB::expr('COUNT("comment.id")'), 'com')

您不希望查詢生成器嘗試並轉義複雜表達式或其他數據庫函數。在這些情況下,您需要使用使用DB::expr創建的數據庫表達式。

+0

這可以使用一點解釋來說明錯誤行的哪一部分被解釋爲一個數組。 –

-1

對於Kohana的2,你想是這樣的

ORM::factory('incident') 
->select('incident.*','COUNT("comment.id") AS comments') 
->join('comment', 'comment.incident_id', 'incident.id', 'LEFT') 
->groupby('incident.id') 
->orderby('comments', 'DESC') 
->find_all(); 

或者使用DB查詢

DB::instance()->query('SELECT incident.*, COUNT(comment.id) AS comments 
FROM incident 
LEFT JOIN comment ON comment.incident_id = incident.id 
GROUP BY incident.id 
ORDER BY comments DESC');