简体   繁体   中英

Codeigniter - join() returns only one “first table”

I have struggle with codeigniter active record in my model.

Problem is that my query returns only one table, my joined table is missing?

    $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();

You need to give unique aliases to your query like array index is unique you can't have two values on same index from your query TITLE will become index of array which has records so try below query,your current results in array form will look something like

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

Because the column name title is same in your both joined tables,you can't have the array like below one with with 2 values on same index

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

Query

$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();

So resultant array will be look something like

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

Try

return $query->result();

Instead of

return $query->result_array();

Or try this way:

$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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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