【问题标题】:Sequelize - Associate a model that is associated with another modelSequelize - 关联与另一个模型关联的模型
【发布时间】:2019-12-16 22:58:48
【问题描述】:

我是 NodeJS + Sequelize 的新手。 我有一个关于关联的问题。

我有 3 个模型:

  • 模型A
  • 型号B
  • 模型C

我有两个关联:

ModelA.belongsTo(ModelB, {as: 'myModelB'});
ModelB.belongsTo(ModelC, {as: 'myModelC'});

现在,我收到了ModelA

router.get('/', (req, res) => {
ModelA.findAll({ include: [ 'myModelB' ]})
    .then(result => {
        res.json(result);
    })
    .catch(err => console.log(err))
});

在回复中我只有modelB的信息,但ModelB没有ModelC的信息

我的结果:

{
  id: 1,
  attr1: 'toto',
  attr2: 'tata',
  myModelB: {
               attrB1: 'Hello',
               attrB2: 'World',
               fk_modelC: 1
            }
}

我想要的结果:

{
  attr1: 'toto',
  attr2: 'tata',
  myModelB: {
               attrB1: 'Hello',
               attrB2: 'World',
               fk_modelC: {
                           attrC1: 'It',
                           attrC2: 'Works!'
                          }
            }
}

当我使用ModelA 时,如何在ModelB 中包含ModelC

【问题讨论】:

    标签: node.js api sequelize.js


    【解决方案1】:

    你要的是:https://sequelize.readthedocs.io/en/latest/docs/models-usage/index.html#nested-eager-loading

    可能是这样的:

    ModelA.findAll({ 
        include: [{
          model: ModelB, 
          as: 'myModelB', 
          include: [{
             model: ModelC,
             as: 'myModelC', 
          }]
       }]
     })
        .then(result => {
            res.json(result);
        })
        .catch(err => console.log(err))
    });
    

    【讨论】:

    • 你在include中丢失了,你必须在include中提到关联的名称,否则会抛出Sequelize Eager Loading错误。
    【解决方案2】:

    使用这个片段:

    router.get('/', (req, res) => {
        ModelA.findAll({
            include: {
                'myModelB',
                include: {
                    'myModelC'
         }
            }
        })
            .then(result => {
                res.json(result);
            })
            .catch(err => console.log(err))
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多