我有两张桌子
posts_table
post_id | user_id | status_message | DATE_TIME
comments_table
comments_id | user_id | post_id | comments_message | DATE_TIME
我的代码是我想要显示每个帖子并在这篇文章中显示所有评论消息
router.get('/', (req, res, next) => {
connection.query('SELECT * FROM photos_status', (err, result) => {
if(err){
console.error(err);
}else{
if(result.length >0){
for(var i = 0; i < result . length ;i++){
var Temp = [];
var post_id =result[i]. post_id;
connection.query('SELECT * FROM comments WHERE post_id = ?',
[post_id], function (error, results) {
if (error) {
res.json({
status:false,
message:'there are some error with query'
})
}else{
res.status(200).json({
result ,
results
});
}
})
}
}
}
});
});
我想从数据库中选择数据并显示如下
[
{ "post_id":"1",
"user_id":"2",
"status_x":"demo ..."
" comments"[
{
"user_id":"1",
"post_id":"1",
"comments_message":"demo..",
},
{
"user_id":"2",
"post_id":"1",
"comments_message":"demo..",
}
]
}
]
答案 0 :(得分:1)
我认为这会给你一些想法:
var allPosts = []
for(var i = 0; i < result.length ;i++){
singlepost={}
singlepost['post_id'] = result[i].post_id;
singlepost['user_id'] = result[i].user_id ;
singlepost['status_x'] = result[i].status_message;
singlepost['comments'] = [];
connection.query('SELECT * FROM comments WHERE post_id = ?',
[post_id], function (error, results) {
if (error) {
res.json({
status:false,
message:'there are some error with query'
})
}else{ res.status(200).json({
//loop over comments create an comment object
comment={}
//same as we did above for singlepost add values and push to array for each element
singlepost['comments'].push(comment)
result ,
results
});
}
}
}
供参考: How to push JSON object in to array using javascript Dynamically Add Variable Name Value Pairs to JSON Object
答案 1 :(得分:0)
if(result.length >0){
var allPosts = []
for(var i = 0; i < result.length ;i++){
var result1;
singlepost={}
singlepost['post_id'] = result[i].post_id;
singlepost['user_id'] = result[i].user_id ;
singlepost['post_message'] = result[i].post_messagecol;
singlepost['comments']=[];
var post_id =result[i]. post_id;
connection.query('SELECT * FROM comment WHERE post_id = ?', [post_id], function (error, results) {
if (error) {
res.json({
status:false,
message:'there are some error with query'
})
}else{
singlepost['comments'].push(results)
console.log(results);
}
});
allPosts.push(singlepost);
}
res.json({
allPosts
});
}
}
});
但输出
{
"allPosts": [
{
"post_id": 1,
"user_id": 1,
"post_message": "hi",
"comments": [
]
}
]
}
console.log(results);
然后评论结果是打印