2015-10-30 34 views
0

我想要的只是符合條件的記錄數(還有其他地方我需要表格中的更多信息,而模型/網關具有這樣做的方法 - 但我想要的只是數字)。使用ZF2數據庫查詢獲取簡單計數值的正確方法是什麼?

使用Zend Framework 2,我只看到兩個選項,我不太找到他們的任何一個可口的解決方案:

一個 - 做一個簡單的選擇 - 我們有高達每天5萬點以上的記錄。

$select = $this->tableGateway->getSql()->select(); 

$select->columns(array(
    "hits" => "id", 
)); 

$select->where->between("timestamp", $start, $end); 

$results = $this->tableGateway->selectWith($select); 

return $results->count(); 

兩個 - 做一個SELECT COUNT() - 然後必須迭代一次結果集並通過模型進行訪問。

$select = $this->tableGateway->getSql()->select(); 

$select->columns(array(
    "hits" => new Expression("COUNT(timestamp)"), 
)); 

$select->where->between("timestamp", $start, $end); 

$results = $this->tableGateway->selectWith($select); 

foreach ($results as $result) { 
    return $result->hits; 
} 

回答

0

多一點思考,並做了類似的查詢,但與其他信息:

$select->columns(array(
     "searches" => new Expression("COUNT(time)"), 
     "successes" => new Expression("COUNT(IF(hits > 0, 1, NULL))"), 
     "failures" => new Expression("COUNT(IF(hits = 0, 1, NULL))"), 
     "suggestions" => new Expression("COUNT(IF(suggestions > 0, 1, NULL))") 
    )); 

我已經想通,這將是最好返回第一個模型中的結果,只是爲了從這些查詢構建信息的一致性。

雖然,我仍然不是100%的這種方法。

相關問題