表 post id content user_id
表 comment id content post_id
前端工程师想要的数据格式:
[
{
"id": "帖子id,整型",
"content": "帖子内容,字符串",
"comments": [
{
"id": "评论ID,整型",
"content": "评论内容,整型",
"post_id": "所属帖子ID,整型",
},
...
]
}
]
node的代码我是这么写的:假设去用户ID=1的帖子
// 上面省略代码...
function Post() {
}
// 获取帖子
Post.getListByUserId = function(userId, callback) {
var query = db.query('SELECT * FROM post WHERE user_id = ?', userId, function(err, posts) {
// 出错
if (err) {
console.log(err);
return;
}
// 遍历帖子 -> 下面的代码是有问题的代码,第一次用Node,按照PHP那种同步的思想来做了,不知道怎么得到前端工程师想要的这样的数据结构????
// 问题1:db.query 是异步的,所以我不知道如何收集结果集
posts.forEach(function(post) {
db.query('SELECT * FROM comment WHERE post_id = ?', post.id, function(err, comments) {
post.comments = comments;
});
});
return callback(posts);
});
}