获取带有评论的帖子的最佳做法是什么?
// get posts
$posts = query('
SELECT id,
content
FROM posts
WHERE author_id = 3
');
// get post ids
$post_ids = [];
foreach ($posts as $post) {
$post_ids[] = $post->id;
}
//get comment
$comments = $this->db->query('
SELECT id,
content
FROM comments
WHERE post_id IN ('.implode(',',$post_ids ).')
');
//Add to post
$comments_by_id = [];
foreach( $comments as $comment ){
$comments_by_id[$comment->post_id][] = $comment;
}
//add comment to post
foreach ($posts as &$post) {
if (isset($comments_by_id[$post->id])){
$post->comments = $comments_by_id[$post->id];
}
}
我也可以使用group_concat
通过1个查询来实现。
SELECT p.id, p.content, GROUP_CONCAT(c.content)
FROM posts p
INNER JOIN comments c ON c.post_id = p.id
WHERE p.author_id = 3
GROUP BY p.id, p.content
最终结果是,$ posts包含id,内容,注释(在数组中)
哪个更好?有更好的方法吗?
答案 0 :(得分:2)
在大多数情况下,当涉及到结构化数据时,让RDBMS进行繁重的工作更为有效。
您似乎正在寻找JOIN
和posts
之间的简单comments
。 FROM
子句应类似于:
FROM posts p
INNER JOIN comments c ON c.post_id = p.id
尚不清楚您要如何在加入后布置数据集,但是由于您提到了GROUP_CONCAT()
,因此这是一个汇总查询,它将为每篇文章返回一条记录,并将所有相应的注释串联在一起(并带有一个,
分隔符):
SELECT p.id, p.content, GROUP_CONCAT(c.content)
FROM posts p
INNER JOIN comments c ON c.post_id = p.id
WHERE p.author_id = 3
GROUP BY p.id, p.content