Welcome Guest, Not a member yet? Register   Sign In
Sum of some fields with Active Record
#1

[eluser]victorche[/eluser]
I have a simple function in a model, which should give me the total number of visitors for a day. Here is my code:
Code:
public function new_guests()
    {
        $today = date('Y-m-d');

        $query = $this->db->from('guests')
                                 ->where('arrival_date', $today)
                                 ->where('status', 'new')
                                 ->get();

        foreach ($query->result_array() as $row)
        {
            $adults[] = (int)$row['adults'];
            $children[] = (int)$row['children'];
            $infants[] = (int)$row['infants'];
        }
        $adults = array_sum($adults);
        $children = array_sum($children);
        $infants = array_sum($infants);

        $total = $adults + $children + $infants;

        return $total . ' (' . $adults . ', ' . $children . ', ' . $infants . ')';
    }
Anyway it looks too complicated and I want to make this using more of the active record... I am reading the user guide and there is a nice select_sum
But as far as I can see... it only works for one column. I need here the sum of 3 different columns. Please, someone to check this code and to give advices.

Thanks!
#2

[eluser]cideveloper[/eluser]
This should work
Code:
$today = date('Y-m-d');
$query = $this->db->select_sum('adults')->select_sum('children')->select_sum('infants')->where('arrival_date', $today)->where('status', 'new')->get('guests');
if ($query->num_rows() > 0){
    $row = $query->row();
    $adults = (int)$row->adults;
    $children = (int)$row->children;
    $infants = (int)$row->infants;
    $total = $adults + $children + $infants;
    return $total . ' (' . $adults . ', ' . $children . ', ' . $infants . ')';
}
return false;




Theme © iAndrew 2016 - Forum software by © MyBB