我有兩個表,一個是張貼表和另一個是評論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();
首先,使用活動記錄,這是有道理的。其次,對於那個輸出,我會使用一個嵌套查詢,也就是在結果循環中查詢帖子和另一個查詢。那麼結果將如此。 – jtheman
@jtheman你能寫一個示例查詢嗎? –
看到下面的答案 – jtheman