序列化-关联与另一个模型关联的模型

时间:2019-12-16 22:58:48

标签: node.js api sequelize.js

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

我有3个型号:

  • ModelA
  • ModelB
  • ModelC

我有两个关联:

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!'
                          }
            }
}

使用ModelC时如何在ModelB中加入ModelA

2 个答案:

答案 0 :(得分: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))
});

答案 1 :(得分:0)

使用此摘要:

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