是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});
});
有更简单的解决方法吗?但我还没有触及迁移。
答案 0 :(得分:3)
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