Codeigniter active record - query 3 tables

不羁的心 提交于 2019-12-25 18:59:08

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/27049336/codeigniter-active-record-query-3-tables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!