简体   繁体   English

CodeIgniter-活动记录联接

[英]CodeIgniter - Active Record join

I got some code in my CodeIgniter model: 我在CodeIgniter模型中得到了一些代码:

        $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. 我想选择所有建筑物,并在可能的情况下加入users_buildings。 The current problem is, that only the buildings with a corresponding entry in users_buildings get selected. 当前的问题是,只有在users_buildings中具有相应条目的建筑物才被选中。

  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 由于第二个join子句将没有level_id(如果该建筑物没有users_buildings可用),则必须进行后备操作才能将join子句更改为buildings_levels.level_id = 0

I hope it's clear what I mean. 我希望我的意思很清楚。 I don't know if that's even possible. 我不知道那是否有可能。

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. 对于缺少的值,它将返回null I don't quite get if you want that null to be a 0 , null or something else. 如果您希望将该null设置为0null或其他值,我不太了解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM