phpmysqlcodeigniterjoinactiverecord

CodeIgniter active record query to JOIN related tables and relate to a fallback row if no related row is found while JOINing


I got some code in my CodeIgniter model:

$this->db->where('building_active', 1);
$this->db->select('*');
$this->db->from('buildings');
$this->db->join('users_buildings', 'users_buildings.building_id = buildings.building_id');
$this->db->join('buildings_levels', 'buildings_levels.level_id = users_buildings.level_id');
$buildings = $this->db->get()->result();

What I want to do:

  1. I want to select all buildings and join users_buildings if possible. The current problem is, that only the buildings with a corresponding entry in users_buildings get selected.

  2. Since there would be no level_id for the second join clause then (if there are no users_buildings available for that building), there would have to be a fallback to change the join clause to buildings_levels.level_id = 0.


Solution

  • Your first question is answered by changing your inner joins into left joins:

    $this->db->join('users_buildings', 'users_buildings.building_id = buildings.building_id', 'left');
    $this->db->join('buildings_levels', 'buildings_levels.level_id = users_buildings.level_id', 'left');
    

    That will return null for the missing values. I don't quite get if you want that null to be a 0, null or something else.