Fetch grouped data from 3 JOINed tables using CodeIgniter's query builder
02:55 05 Aug 2021

I am working with mysql and php and I want to get data according to "city" in array Here is my table "merchants"

merchantid              localityId
1                           30                       
2                           30       
3                           31
4                           30
5                           32

Here is table "locality"

localityId               cityId           name
30                          1              abc 
31                          1              xyz
32                          2              xya

Here is table "city"

cityId                  name
1                       Chandigarh
2                       Panchkula
3                       Delhi
4                       Mumbai

And I want to fetch data according to "city/locality",For example I want to fetch all record of city(group by city), in other words I want it like the following output. How can I do this?

{
    "Status": "1",
    "data": [
        {
            "localityName": "Chandigarh",
            "FilterType": "filter",
            "result": [
                {
                    "id": "1",
                    "name": "",
                    //other info
                },
                {
                    "id": "2",
                    "name": "",
                    //other info
                },
           "localityName": "Panchkula",
            "FilterType": "filter",
            "result": [
                {
                    "id": "3",
                    "name": "",
                    //other info
                },
                {
                    "id": "4",
                    "name": "",
                    //other info
                },  
                ...And so on   
         }       

I tried with following code but giving me list of locality/city, not giving me result as I want. Where am I going wrong?

$this->db->select('l.localityId,c.name,c.cityId');
$this->db->from('merchants m'); 
$this->db->join('locality l', 'l.localityId=m.localityId');
$this->db->join('city c', 'c.cityId=l.cityId');
$this->db->group_by('l.cityId');         
$query = $this->db->get(); 
if ($query->num_rows() != 0) {
    return $query->result_array();
} else {
    return false;
}
php codeigniter join grouping query-builder