2016-05-12 104 views
0

我有两个表,一个是张贴表和另一个是评论table.in我使用post_id作为foreign_key。 现在我想得到一个包含所有评论的帖子。并且回应应该采用这种格式。从codeigniter中的多个表中获取数据?

{ 
    "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(); 
+0

首先,使用活动记录,这是有道理的。其次,对于那个输出,我会使用一个嵌套查询,也就是在结果循环中查询帖子和另一个查询。那么结果将如此。 – jtheman

+0

@jtheman你能写一个示例查询吗? –

+0

看到下面的答案 – jtheman

回答

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 

例如

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

您可以通过使用行SQL或活动记录连接这两个表来完成此任务。

由于

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

希望这将有助于..

谢谢!