2011-10-07 51 views
2

我在數據庫中存儲數量的值(int)。我需要通過將所有行總計加在一起來計算總數量。 $ this-> db-> count_all_results()的問題是它返回的是總行數,但不計算所有存儲的值。任何幫助將非常感激。用Codeigniter Active Record計算行總數

function currentDealTotalQuantity($id) 
{ 

    $this->db->select('quantity'); 

    $this->db->from('table'); 

    $this->db->where('id', $id); 

    $total_sold = $this->db->count_all_results(); 

    if ($total_sold > 0) 
    { 
     return $total_sold; 
    } 

    return NULL; 

} 

回答

3
function currentDealTotalQuantity($id) 
{ 

    $this->db->select_sum('quantity'); 

    $this->db->from('table'); 

    $this->db->where('id', $id); 

    $query = $this->db->get(); 

    $total_sold = $query->row()->quantity; 

    if ($total_sold > 0) 
    { 
     return $total_sold; 
    } 

    return NULL; 

} 
+0

收到此錯誤:類CI_DB_mysql_result的對象無法轉換成int – undertokyo

+0

編輯。現在請嘗試這個。 –

+0

就是這樣!謝謝。 – undertokyo

3

我相信你想這個傢伙:$this->db->select_sum();

你用它取代你的SELECT語句,讓你有$this->db->select_sum('quantity');這將產生的查詢字符串SELECT SUM(quantity) as quantity

的文檔中找到here

2
function currentDealTotalQuantity($id) 
{ 
    $qry = $this->db->select_sum('quantity') 
    ->from('table') 
    ->where('id', $id) 
    ->get(); 

    if ($qry->num_rows() === 0) 
    { 
     return FALSE; 
    } 

    return $qry->row('quantity'); 
} 
相關問題