Codeigniter - join()只返回一个“第一个表”


Codeigniter - join() returns only one "first table"

我在模型中与codeigniter活动记录作斗争。

问题是我的查询只返回一个表,我的连接表丢失了吗?

    $this->db->select("page.ID, page.TITLE, category.TITLE");
    $this->db->from('page');
    $this->db->join('category','page.ID_CATEGORY = category.ID');
    $query = $this->db->get();
    return $query->result_array();

你需要为你的查询提供唯一的别名,比如数组索引是唯一的,你不能在同一索引上有两个值,从你的查询TITLE将成为有记录的数组的索引,所以尝试下面的查询,你当前的数组形式的结果将看起来像

array(
[0] => array(
['ID'] => 1,
['title'] => test page
)
[1] => ...
)

因为两个连接表的列名标题相同,所以不能像下面这样在同一个索引上有两个值的数组

array(
[0] => array(
['ID'] => 1,
['title'] => test page,
['title'] => test cat /* wrong index */
)
[1] => ...
)
查询

$this->db->select("page.ID, page.TITLE AS page_title, category.TITLE AS cat_title");
$this->db->from('page');
$this->db->join('category','page.ID_CATEGORY = category.ID');
$query = $this->db->get();

那么最终的数组看起来就像

array(
[0] => array(
['ID'] => 1,
['page_title'] => test page,
['cat_title'] => test cat,
)
[1] => ...
)

Try

return $query->result();

代替

return $query->result_array();

或者这样试试:

$this->db
        ->select('ID')
        ->from('table2');

$subquery = $this->db->_compile_select();
$this->db->_reset_select(); 
$query  =       $this->db
                    ->select('t1.name')
                    ->from('table1 t1 ')
                    ->join("($subquery)  t2","t2.id = t1.t2_id")
                    ->get('table1 t1');
相关文章: