2017-10-12 53 views
0

我使用nodejs工作後綴,我嘗試將我的查詢代碼從mysql查詢轉換爲sequelize語法你能幫我解決這個問題嗎?將查詢從mysql客戶端轉換爲續集語法

MySQL查詢:

select username,message,fromUserId,toUserID from messages inner join messageToUsers on messages.id = messageToUsers.messageID left outer join users on messages.fromUserID = users.id where messageToUsers.`toUserID` = 5 and messages.`fromUserId` = 7 or messageToUsers.`toUserID` = 7 and messages.`fromUserId` = 5 

sequlize查詢

Message.hasMany(MessageToUser,{foreignKey:'messageID'}); 
    Message.belongsTo(Users,{foreignKey:'fromUserId'}); 
    Message.findAll({where:{fromUserId :5,fromUserID : 7}, 
     include :[ 
      {model:MessageToUser,where:{toUserID:5,toUserID:7}} , 
      {model:Users,attributes:['id','username']} 
     ] 

    }).then(function(messages) { 
     console.log(JSON.stringify(messages)); 
     res.status(200).json(messages); 


    }) 

回答

0

你缺少你的屬性

Message.hasMany(MessageToUser,{foreignKey:'messageID'}); 
Message.belongsTo(Users,{foreignKey:'fromUserId'}); 
Message.findAll({where:{fromUserId :5,fromUserID : 7}, 
    include :[ 
     {model:MessageToUser,where:{toUserID:5,toUserID:7}} , 
     {model:Users,attributes:['id','username']} 
    ], 
    attributes: ["username","message", "toUserId", "fromUserId"] //<-HERE 

}).then(function(messages) { 
    console.log(JSON.stringify(messages)); 
    res.status(200).json(messages); 


}); //<- you also missed a semicolon here. 

我注意到第二件事。如果您在where的相同型號中使用相同的字段兩次,其中一個將被忽略。您需要使用$and

{model:MessageToUser,where:{ 
    $and: {[toUserID:5], 
      [toUserID:7]} 
}} 

注:在聲明的末尾缺少分號通常不會導致應用程序失敗,但是一致的最佳實踐,可以一直使用它們或總是忽略它們。

0

我解決了這個問題,感謝大家

Message.hasMany(MessageToUser,{foreignKey:'messageID',as: 'model1'}); 
    Message.belongsTo(Users,{foreignKey:'fromUserId'}); 
    Message.findAll({where:{$or:[{'$model1.toUserId$':toUserId,fromUserId:fromUserID},{'$model1.toUserId$':fromUserID,fromUserId:toUserId}]}, 
     include :[ 
      {attributes: ["toUserId"],model:MessageToUser,as: 'model1'} , 
      {attributes: ["username"],model:Users} 
     ] 

    }).then(function(messages) { 
     console.log(JSON.stringify(messages)); 
     res.status(200).json(messages); 


    });