2016-12-25 25 views
2

是Node J和相關程序的新功能。目前正試圖創建一個應用程序,上傳帶有標題等圖像,並供用戶喜歡和評論(更像Instagram /臉書)。到目前爲止,我的應用程序可以正常工作,但現在我試圖從多個表中拉出多個值,將值作爲數組中的對象傳遞並呈現在新的EJS文件中。以下是代碼Sequelize從多個表中提取數據並將其作爲對象傳遞給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

所以從多次嘗試和更多的研究解決方案我突然明白了,多虧了答案後[鏈接](http://stackoverflow.com/questions/ 33970624 /查詢,多型號與 - sequelize-JS-ORM) – Prince

回答

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

相關問題