CodeIgniter Self-Join与SQL不匹配

时间:2012-08-15 16:21:06

标签: php sql codeigniter

好吧,这里不得不遗漏一些东西。

我的SQL工作正常:

SELECT t1.id, t1.material, t2.id, t2.material, t3.id, t3.material, t4.id, t4.material
FROM ml_levels t1 

LEFT JOIN ml_levels t2 
ON t1.parentID = t2.id

LEFT JOIN ml_levels t3
ON t2.parentID = t3.id

LEFT JOIN ml_levels t4
ON t3.parentID = t4.id

WHERE t1.id = 286

返回

id   |  material  | id  |  material         |  id  |  material            | id |  material
-------------------------------------------------------------------------------------------
286  |  4Layer    | 209 |  Protective Film  |  60  |  Specialty Products  | 1  |  Protect 

但是,我的ActiveRecord只返回t4.id和t4.material:

    $this->db->select('t1.id, t1.material, t2.id, t2.material, t3.id, t3.material, t4.id, t4.material');
    $this->db->from('ml_levels AS t1')->where('t1.id',286);
    $this->db->join('ml_levels AS t2','t1.parentID = t2.id','left');
    $this->db->join('ml_levels AS t3','t2.parentID = t3.id','left');
    $this->db->join('ml_levels AS t4','t3.parentID = t4.id','left');

    return $this->db->get()->row();

返回:

id   |  material  |
-------------------
1    |  Protect   |

$ this-> db-> last_query()返回:

SELECT `t1`.`id`, `t1`.`material`, `t2`.`id`, `t2`.`material`, `t3`.`id`, `t3`.`material`, `t4`.`id`, `t4`.`material` 
FROM (`ml_levels` AS t1) 
LEFT JOIN `ml_levels` AS t2 ON `t1`.`parentID` = `t2`.`id` 
LEFT JOIN `ml_levels` AS t3 ON `t2`.`parentID` = `t3`.`id` 
LEFT JOIN `ml_levels` AS t4 ON `t3`.`parentID` = `t4`.`id` 
WHERE `t1`.`id` = 286 

如果我在数据库上运行此SQL,它将返回原始查询返回的内容。

1 个答案:

答案 0 :(得分:1)

Codeigniter仅返回没有表格标签的字段名称,因此您只找到两个字段,因为只有idmaterial。更改行:

 $this->db->select('t1.id, t1.material, t2.id, t2.material, t3.id, t3.material, t4.id, t4.material'); 

使用:

 $this->db->select('t1.id AS t1id, t1.material AS t1material, t2.id AS t2id, t2.material AS t2material, t3.id AS t3id, t3.material AS t3material, t4.id AS t4id, t4.material AS t4material');