【问题标题】:Sequelize js 'include' and 'raw'续集 js 'include' 和 'raw'
【发布时间】:2017-04-13 23:56:15
【问题描述】:

我有两个实体之间的关系,例如(每个箱子都有一个用户)

entities.Chest.belongsTo(entities.User)

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

entities.Chest.findAll({include:[{model: entities.User}]})

但我更喜欢将它们作为普通对象来操作,我愿意

entities.Chest.findAll({raw:true, include:[{model: entities.User}]})

而且结果根本不包括用户,我该如何实现呢?

【问题讨论】:

    标签: javascript node.js sequelize.js


    【解决方案1】:

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

    entities.Chest.findAll({
        raw:true,
        nest: true,
        include:[entities.User]
    })
    

    【讨论】:

    • 谢谢。 'nest: true' 是使用 async 和 await 时的必需项。
    • 这应该是公认的答案!
    【解决方案2】:

    如您所见,raw 在连接方面存在一些问题(有一个issue) 尝试使用实例方法#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
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      • 2021-08-15
      • 1970-01-01
      • 2015-04-10
      • 2017-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多