Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

php - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...