2016-05-12 106 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(); 
    } 

希望這將有助於..

謝謝!