phpcodeigniterdata-structuresgroupingquery-builder

How to group JOINed data with a one-to-many relationship into subarrays to avoid duplicating parent level data with CodeIgniter


I am having a play around with CodeIgniter and trying to get my head around the query builder system.

I have set up a couple of tables and am attempting to run a join on them, as such:

function GetOrganisationsAndBuildingDetails()
{
    $this->db->select('
        organisations.organisation_name,
        organisations.organisation_id,
        buildings.building_name,
        buildings.address1
    ');
    $this->db
        ->from('organisations')
        ->join('buildings', 'buildings.organisation_id = organisations.organisation_id');
    $query = $this->db->get();
    return $query->result();
}

In my database, I have one organisation with two related buildings. The above query returns two objects (one for each building) - however, the organisation is duplicated.

I suppose I was expecting something along the lines of one return object with a series of nested objects for related buildings. Is this possible? If not, is their a recommend way of arranging the return data so I can easily loop through it in the view? (foreach org, foreach building etc etc).

Apologies if I'm being a little dense here. I'm coming from .net and (linq to SQL in particular) where this stuff is a little different).


Solution

  • The query will inevitably return duplicate data as you say, you have to organize them after you get the result like this

    $buildings = array();
    
    foreach ( $result_object as $organization ) {
        $building_data = array(
            'building_name' => $organization->building_name,
            'address'       => $organization->address,
        );
        $buildings[$organization->organization_name][] = $building_data;
    }
    

    this way organizations will be "compacted" in the first key of the multidimensional array, and one level deeper you will have info about the buildings. Hope this helps.