gpt4 book ai didi

javascript - Sequelize 从多个表中提取数据并作为对象传递以在 EJS 中呈现

转载 作者:搜寻专家 更新时间:2023-10-31 23:46:13 26 4
gpt4 key购买 nike

我是 Node Js 和相关程序的新手。目前正在尝试创建一个应用程序来上传带有字幕等的图像并供用户点赞和评论(更像是 instagram/facebook)。到目前为止,我的应用程序可以正常工作,但现在在尝试从多个表中提取多个值、将这些值作为数组中的对象传递并在新的 EJS 文件中呈现时卡住了。下面是代码

 app.get('/pages/photos/:id', function (req, res){
//show photos with comments
//1. photo with id :id
// 2. all comments associated with id :id
//likes associated with photo
var photoId=req.params.id;
var photoData = []
Photos.findOne({
where:{id: photoId},
attributes: ['userId','filename', 'caption', 'createdAt']
}).then(function (rowPhoto){
photoData.photoValues = []
var vals = {
photoId:photoId,
userId:rowPhoto.userId,
photoName: rowPhoto.filename,
caption:rowPhoto.caption,
createdAt:rowPhoto.createdAt
}
photoData.photoValues.push(vals);
console.log("#1 "+ rowPhoto.caption);

}).then(function(){
Comments.findAll(
{where:
{photoId:photoId}
}).then(function(rowComments){
photoData.photoComments= []
for (i=0; i < rowComments.length ; i++){
vals = {
id: rowComments[i].id,
userId: rowComments[i].userId,
text:rowComments[i].comment,
createdAt:rowComments[i].createdAt
}
photoData.photoComments.push(vals);
}
console.log("#2 "+ rowComments.length);
});
}).then(function(){
Likes.findAll({
where:{photoId:photoId}
}).then(function(rowLikes){
photoData.photoLikes= []
for (i=0; i < rowLikes.length ; i++){
vals = {
id: rowLikes[i].id,
liked: rowLikes[i].liked,
userId:rowLikes[i].userId,
photoId:rowLikes[i].photoId
}
photoData.photoLikes.push(vals);

}
console.log("#3 " + rowLikes[i]);

});
});
console.log("#4 " + photoData);
//res.render('views', {views:photoData});
});

有没有更简单的方法来解决这个问题?不过,我还没有接触过迁移。

最佳答案

    Photos.findOne({
where:{id: photoId},
attributes: ['id','userId','filename', 'caption', 'createdAt']
}).then(function (rowPhotos){
Comments.findAll({
where: {photoId:photoId}
}).then(function (rowComments){
Likes.findAll({
where: {photoId: photoId}
}).then(function (rowLikes){
Users.findAll().then(function (commentUser){
var data= {
photoData: rowPhotos,
commentData: rowComments,
likesData: rowLikes,
userData:commentUser
}
console.log(data);
res.render('views', {data:data})

})

})
})
})

});

此解决方案由以下链接提供: Querying multiple models with Sequelize.js ORM

关于javascript - Sequelize 从多个表中提取数据并作为对象传递以在 EJS 中呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41324800/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com