【问题标题】:Reorganize Sequelize results重组 Sequelize 结果
【发布时间】:2016-04-12 00:30:27
【问题描述】:

我在 Sequelize 中制作了一个复杂的 findAll,其中包含很多 includes,就像这样。

const versions = yield Version.findAndCountAll({
  order: [['createdAt', 'DESC']],
  attributes: ['description', 'createdAt', 'id'],
  include: [{
    model: Section,
    attributes: ['slug'],
    where: { slug: section },
    include: [{
      model: Type,
      attributes: ['slug'],
      where: { slug: type },
      include: [{
        model: Group,
        attributes: ['slug'],
        where: { slug: group }
      }]
    }]
  }]
});

结果如下:

{
  "description": "Wow. Nice one.",
  "createdAt": "2016-04-11T23:05:15.736Z",
  "body": "hi",
  "id": 10,
  "Section": {
    "slug": "ttyl",
    "Type": {
      "slug": "Test",
      "Group": {
        "slug": "python2",
      }
    }
  }
}

它们嵌套的深度使结果有点令人不快。如果可能的话,我希望它更像这样

{
  "description": "Wow. Nice one.",
  "createdAt": "2016-04-11T23:05:15.736Z",
  "body": "hi",
  "id": 10,
  "Section": "ttyl",
  "Type": "Test",
  "Group": "python2"
}

这可能吗?

【问题讨论】:

    标签: javascript node.js sequelize.js


    【解决方案1】:

    您可以通过设置 raw:true 将其展平到某种程度。 Raw true 将展平为 model.subproperty.property 等。include 'as' 选项允许您在这些属性上使用别名。但我不相信您可以自动完全重塑对象(至少我在文档中没有发现任何内容)。从上面的示例中,我相信最终您必须添加自己的映射步骤。

    Model.findAndCountAll({
      ...
    }).then(function(results){
         return results.map(function(items){
             //map into another "object'
             //or into anonymous {};
         });
    });
    

    【讨论】:

    • 您可以复制您共享的链接的相关部分以供后代使用吗?
    • @Noah 澄清/更新了我关于扁平化的 cmets。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 2019-10-05
    • 2016-07-11
    相关资源
    最近更新 更多