简体   繁体   中英

Codeigniter active record - query 3 tables

I need to make a query using 3 tables and i having some trouble with that. I have 3 tables in my project:

projects , projects_categories and categories

projects

  • id_project
  • title
  • date

projects_categories

  • id_proj_cat
  • id_project
  • id_category

categories

  • id_category
  • name

I already made a join query but the result is a array with the same project_id showing several times. What i need is a more efficient query that can list for each project_id a array inside, with it´s categories and names. Something like that.

I can make a separate query but im trying to achieve that in one single query.

Try this

    $this->db->from("projects p");
    $this->db->select("p.id_project,c.categories,c.name");
    $this->db->join("projects_categories pc","pc.id_project = p.id_project","LEFT");
    $this->db->join("categories c","c.id_category = pc.id_category","LEFT");
    $result=$this->db->get()->result_array();

Now $result is your array.

Try this one:

$this->db->select('p.id_project,c.categories,c.name');
$this->db->from('projects p');
$this->db->join("projects_categories pc","p.id_project = pc.id_project","INNER");
$this->db->join("categories c","pc.id_category = c.id_category","INNER");
$query = $this->db->get();
return $query->result_array();

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