1
我目前從我的'social_posts'表中獲取詳細信息,然後添加它的標籤,喜歡的數量以及它對結果對象的答案數量。有沒有辦法可以做到這一點,而不必在循環中做額外的查詢?安排JOIN數據庫結果
$query = "SELECT * FROM social_posts JOIN users ON social_posts.user_id = users.id";
$posts = $this->db->query($query);
if ($posts->num_rows() > 0) {
foreach ($posts->result() as $p => $post) {
// Get the question's tags
$tags = $this->db->query("SELECT * FROM social_tags
WHERE post_id = ?", $post->post_id);
// Get the number of likes
$likes = $this->db->query("SELECT id FROM social_likes
WHERE post_id = ?", $post->post_id);
// Get the number of answers
$answers = $this->db->query("SELECT id FROM social_responses
WHERE post_id = ?", $post->post_id);
$post->tags = $tags->result();
$post->likes = $likes->num_rows();
$post->answers = $answers->num_rows();
$post->author = array(
"firstname" => $post->firstname,
"thumbnail" => $post->thumbnail,
);
}
return $posts->result();
} else {
return FALSE;
}
非常感謝,這太棒了!它似乎沒有顯示任何回覆的帖子,但?我在哪裏指定「WHERE」子句? – Sneaksta
1)在您的原始代碼中,據我所知,您只能得到響應的數量。爲後續查詢獲取給定帖子的所有回覆可能是一個更好的主意,因爲可能需要更多來自social_responses表的列。 – oujesky
2)WHERE子句在FROM和GROUP BY子句之間獲取 – oujesky