sequelize包括创建嵌套对象

时间:2016-05-23 07:04:29

标签: node.js sequelize.js

我想从模型用户到模型团队进行内部联接。 这是代码:

User.findAll({
  arrtibute: ['name'],
  include: [{
    model: Team,
    arrtibutes: ['teamName']
  }]
})

然后,我得到:

[ 
  { 
    name: 'wrq',
    team: {
      teamName: 'teamA'
    }
  },
  { 
    name: 'wyx',
    team: {
      teamName: 'teamB'
    }
  },
]

但我的期望是:

[ 
  { 
    name: 'wrq',
    teamName: 'teamA'
  },
  { 
    name: 'wyx',
    teamName: 'teamB'
  },
]

我怎么能通过续集来做到这一点?

1 个答案:

答案 0 :(得分:3)

您可以简单地映射值。

User.findAll({
    attributes: ['name'],
    include: [{
        model: Team,
        attributes: ['teamName']
    }]
}).then(function(users) {
    return users.map(function(user) {
        return {
            name: user.name,
            teamName: user.team.teamName
        }
    });
}).then(function(users) {
    // The rest of your logics here...
});