phpcodeigniterjoinactiverecordalias

How to prevent SELECT clause column name collisions after joining tables in CodeIgniter


This is my model:

function getGalleryListing()
{
    $this->db->select('photo.id,photo.src,photo.title,photo.user_id,users.id,users.username');
    $this->db->from('photo');
    $this->db->join('users', 'users.id = photo.user_id');
    $query = $this->db->get();
    return $query->result();
}

And my controller:

function index()
{       
    $data['gallery_list'] = $this->Gallery_model->getGalleryListing();
    $data['content'] = $this->load->view('gallery/index', $data, true);
    if ($this->dx_auth->is_logged_in()) 
    {

        $this->load->view('template_login', $data);
    }
    else
    {
        $this->load->view('template', $data);
    }
}

The problem is, when I do <?= $gallery->id ?>, it keeps showing me the ID from USERS.ID instead of PHOTO.ID. Did I miss out something?


Solution

  • You are selecting two ids (from photo and users) and only the later is shown. You need to use alias with As to assign a different name to one of the ids and this way it will show you required id successfully. For example, your query should look like this:

    select (photo.id) as photo_id,photo.src,photo.title,photo.user_id,users.id,users.username from photo inner join users on users.id = photo.user_id
    

    Now <?= $gallery->photo_id ?> will give you the photo id and <?= $gallery->id ?> will give you userid.

    Note: You can modify above query in CI's perspective or use as it is if you can. Thanks