Sequelize js'include'和'raw'

And*_*ley 5 javascript node.js sequelize.js

我有两个相似的关系(每个胸部有一个用户)

entities.Chest.belongsTo(entities.User)
Run Code Online (Sandbox Code Playgroud)

我想在一个查询中检索所有的箱子及其用户,所以我这样做

entities.Chest.findAll({include:[{model: entities.User}]})
Run Code Online (Sandbox Code Playgroud)

但是我喜欢把它们当作普通物体来操纵

entities.Chest.findAll({raw:true, include:[{model: entities.User}]})
Run Code Online (Sandbox Code Playgroud)

而结果根本不包括用户,我该如何实现这一目标?

Rud*_*chi 5

如你所见,raw有一些连接问题(有一个问题)尝试使用实例方法#toJSON

entities.Chest.findAll({include:[{model: entities.User}]})
  .then(function(chestsSeq){
    var chests = chestsSeq.toJSON(); //same as chestsSeq.get({});
    //do something with raw chests object
  });
Run Code Online (Sandbox Code Playgroud)


小智 5

这种语法对我有帮助。你不必迭代你的记录。只需成对使用nest: trueraw: true

entities.Chest.findAll({
    raw:true,
    nest: true,
    include:[entities.User]
})
Run Code Online (Sandbox Code Playgroud)

  • 谢谢。使用 async 和 await 时,“nest: true”是必需的。 (3认同)