phpmysqlcodeigniteractiverecordsum

CodeIgniter fetch data from 2 tables and sum


I have two db tables clients and bookings

Clients table contains:

[client_ref] [client_name]
 2378       | My Client
 8746       | Other Client

Bookings table contains

[booking_client] [booking_num]
 2378           | 1
 2378           | 5
 8746           | 3

Currently in model i have this query

function clients()
{
    $query = $this->db
        ->select('*')
        ->order_by('client_name', 'ASC')
        ->get('clients');
    return $query->result();
}

Then controller to set $data value

$data['clients'] = $this->home_model->clients();
$this->load->view('pages/clients', $data);

And in view

foreach ($clients as $client)
{
echo $client->client_name . " - " .$client->client_ref . "<br />";
}

It currently displays list of clients (name - ref).

I want to make model to query those 2 tables, SUM booking_num and order record by SUM descending.


Solution

  • You have to use the group by and sum SQL functions, as below

    $this->db->select('clients.client_ref, clients.client_name, sum(bookings.booking_num) as sum_booking_num');
    $this->db->from('clients');
    $this->db->join('bookings', 'bookings.booking_client = clients.client_ref', 'right');
    $this->db->group_by('clients.client_ref');
    $this->db->order_by('sum_booking_num', 'desc');
    $clients = $this->db->get()->result_object();
    

    Click here for demo.