【问题标题】:In sequelize.js, is it possible to un-nest the results of a query with nested includes?在 sequelize.js 中,是否可以使用嵌套包含取消嵌套查询的结果?
【发布时间】:2017-10-02 20:24:03
【问题描述】:

我希望能够将我的包含嵌套在查询中,但我希望结果不是嵌套的。

例如:

db.a.findAll({
    where: {id: id},
    include: [
        { model: db.b, include: [
            { model: db.c, include: [
                { model: db.d }
            ]}
        ]}
    ]
})
...

返回如下内容:

[
    {
        a: {
            ...
            b: {
                ...
                c: {
                    ...
                    d: {
                        ...
                    }
                }
            }
        }
    }
]

但我想要这个:

[
    {
        a: {
            ...
            b: {
                ...
            },
            c: {
            ...
            },
            d: {
                ...
            }
        }
    }
]

在不重构模型/表的情况下这是否可能?

【问题讨论】:

    标签: mysql node.js orm sequelize.js


    【解决方案1】:

    我发现了如何做到这一点,但这并不是最理想的方法。您可以像这样手动重新链接对象:

    db.a.findAll({
        where: {id: id},
        include: [
            { model: db.b, include: [
                { model: db.c, include: [
                    { model: db.d }
                ]}
            ]}
        ]
    }).then(function(a) {
        //you may need to iterate over an array
        a.setDataValue('d', a.b.c.d);
        a.b.c.setDataValue('d', null);
        a.setDataValue('c', a.b.c);
        a.b.setDataValue('c', null);
    }
    

    【讨论】:

      【解决方案2】:

      你只需要一个包含,然后你就可以嵌套所有你需要的模型:

      db.a.findAll({
          where: {id: id},
          include: [
              { 
                  model: db.b
              },{
                  model: db.c
              },{
                  model: db.d
              }
          ]
      })
      

      【讨论】:

      • 是的,但是 a 与 c 或 d 没有关联,只能像这样链接它们:a -> b -> c -> d
      • 据我所知是不可能的,因为 include 是表之间的连接,如果你没有模型之间的关联,那么唯一的选择就像你首先做的那样,至少不是在续集.js
      猜你喜欢
      • 2016-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-30
      • 2019-10-24
      • 1970-01-01
      • 2011-12-01
      相关资源
      最近更新 更多