从codeigniter中的多个表中获取数据?

时间:2016-05-12 12:53:42

标签: php mysql codeigniter

我有两个表,一个是post表,另一个是comment table.in我使用post_id作为foreign_key。 现在我想得到一个包含所有评论的帖子。并且响应应采用这种格式。

 { 
    "posid":1,
    "post_name":"testpost",
    "comments":[{
                    "comment_id":1,
                    "comment_des":"testcoment"
                },{
                    "comment_id":2,
                    "comment_des":"testcoment2"
                }
            ]
    }

对于这种类型的响应,任何人都可以为我编写简单的SQL查询吗?

我在codeigniter中尝试了以下查询,但这会返回多个结果,意味着一次发布两次,因为一个帖子包含两条评论。

  $this->db->select("p.post_id,p.post_desc,p.post_time ,c.id,c.comment_desc,c.comment_time");
  $this->db->join("asoc_comments as c","p.post_id = c.post_id","INNER");
 $response = $this->db->get("asgn_posts as p")->result();

3 个答案:

答案 0 :(得分:1)

活动记录示例,我们循环结果以便格式化输出,而不会为每个帖子获取多个结果行:

$q = $this->db->select('post_id,post_desc,post_time')->get('asgn_posts');
$data = array();
foreach ($q->results() as $p):
   $qc = $this->db->select('id,comment_desc,comment_time')->where('post_id',$p->post_id)->get('asoc_comments');
   $p->comments = $qc->results();
   $data[] = $p;
endforeach;
return $data;

答案 1 :(得分:0)

您可以编写此查询以显示结果:

SELECT p.post_id as 'posid',p.post_name,(SELECT c.id as 'comment_id' , c.comment_desc as 'comment_des' from asoc_comments c where c.post_id = p.post_id) as 'comments' from asgn_posts p

<强> E.g。

$response=$this->db->query("SELECT p.post_id as 'posid',p.post_name,(SELECT c.id as 'comment_id' , c.comment_desc as 'comment_des' from asoc_comments c where c.post_id = p.post_id) as 'comments' from asgn_posts p")->result();

答案 2 :(得分:0)

您可以使用Row SQL或Active record连接这两个表来执行此任务。

作为

public function your_model_method(){
    $this->db->select('table_1.*,table_2.*')->from('table_1');
    $this->db->join('table_2','table_2.key_field=table_1.key_field');
    return $this->db->get()->result_array();
    }

希望它会有所帮助..

谢谢!