如何使用sequelize findAll()获取数组中的关联?

问题描述 投票:0回答:1

我对 Sequelize 还很陌生,并试图学习所有可以用来格式化查询的很酷的技巧,但遇到了一些困难。

基本上我有一张“发票”表。我有另一个表“invoice_items”,其中许多发票_项目与一张发票有关系。

目前我正在尝试在 findAll 查询中包含此一对多关联,以便发票_项目嵌套在每个发票对象的数组中。

大致如下:

[
  {
    name: invoice1
    invoiceItems: [
      itemOne,
      itemTwo,
    ]
  },
    {
    name: invoice2
    invoiceItems: [
      itemOne,
      itemTwo,
    ]
  }
]

我能得到的最接近的是输出多个发票对象(每个关联一个)。这是查询,它输出下面的对象。

db.invoice.findAll({
    where: {
        userId: req.user.id
    },
    include: "invoiceItems",
    raw : true,
    nest : true
});
[
  {
    name: invoice1
    invoiceItems: itemOne
  },
  {
    name: invoice1
    invoiceItems: itemTwo
  },
  {
    name: invoice2
    invoiceItems: itemOne
  },
  {
    name: invoice2
    invoiceItems: itemTwo
  }
]

有什么办法可以实现我希望在这里实现的目标吗?预先感谢!

编辑:

我能够通过使用 get() 来帮助处理结果来获得所需的结果。我遇到的问题很原始: true 似乎不适用于急切加载。

这是已处理的选项,以防有人觉得有帮助。

db.invoice.findAll({
    where: {
        userId: req.user.id
    },
    include: "invoiceItems",
}).then(results => {
    let processedResults = [];
    for (result of results){
        processedResults.push(result.get({ plain: true }));
    }
    return processedResults;
});

这并不理想,但目前已经完成了工作。不过,我仍然对更优雅的解决方案感兴趣!

node.js postgresql sequelize.js
1个回答
0
投票

如果您想进一步简化代码,可以如下所示:

db.invoice.findAll({
    where: {
        userId: req.user.id
    },
    include: [{model: invoiceItems}]
}).then(results => results);
  • 省略 plain: true,默认情况下 Sequelize 返回一个对象数组,因此不需要定义为“processedResults”的数组
  • (results => results) 是 ES6 的简写 results => { return results }
© www.soinside.com 2019 - 2024. All rights reserved.