简体   繁体   中英

select records form tableA and tableB where tableA.id = tableB.id, records from tableA once

I am working in Codeigniter. I have two tables in MySql database "menus" and "menus_child". The structure is:

table: menus

id | menu_name
1 | products

table: menus_child

child_id | id | child_name
1 | 1 | product1
2 | 1 | product2
3 | 1 | product3

What I want to achieve is, Select the "id, menu_name" from "menus" and also with it Select "child_name" from "menus_child" Where menus.id = menus_child.id. Remeber its "id" as in table "menus" and not "child_id" as in table "menus_child"

Here is what I am doing:

$this->db->select('menu_name');    
      $this->db->from('menus');
      $this->db->select('child_name');
      $this->db->from('menus_child');
      $this->db->where('menus.id = menus_child.id');
      $query = $this->db->get();
      $data = $query->result();
      return $data;



However, this query returns

        [0] => stdClass Object
            (
                [menu_name] => products
                [child_name] => product1
            )

        [1] => stdClass Object
            (
                [menu_name] => products
                [child_name] => product2
            )

        [2] => stdClass Object
            (
                [menu_name] => products
                [child_name] => product3
            )

But I want it to be something like this:

[0] => stdClass Object
            (
                [menu_name] => products
                [child_name] => product1
                [child_name] => product2
                [child_name] => product3
            )



Any kind of help will be much appreciated.

$sql=$this->db->query(
"SELECT * from menus ");
$data=$sql->result_array();
foreach($data as $key=>$mainmenu){
$data[$key]['child']=$this->getChild($mainmenu['id']);
}
return $data;

function getChild($menu_id){
   $sql=$this->db->query(
    "SELECT * from menus_child where id='$menu_id'");
 $data=$sql->result_array();
return $data;
}

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