最常见的第一次尝试是(伪代码):
posts = SELECT * FROM posts
for each (post in posts) {
post[comments] = SELECT * FROM comments WHERE post_id = {post[id]}
}
但是最好有 JOIN,对吧?(或不?告诉我)所以:
posts = SELECT * FROM posts JOIN comments ON comments.post_id = posts.id
所以结果将是这样的:
post_id | post | comment_id | comment
===============================================
1 | foo | 1 | nice foo
1 | foo | 2 | dont like ur foo
2 | bar | 3 | bar is better
如何转换为这个?
array(
array(
'id' => 1,
'post' => 'foo',
'comments' => array(
array('id' = 1, 'comment' => 'nice foo'),
array('id' = 2, 'comment' => 'dont like ur foo'),
)
),
array(
'id' => 2,
'post' => 'bar'
'comments' => array(
array('id' = 1, 'comment' => 'bar is better')
)
),
);
谢谢!