Sequelize和嵌套结果?

时间:2016-05-09 18:26:32

标签: javascript node.js sequelize.js

Sequelize允许数据关系,但我似乎无法看到是否有办法让它返回由关系组成的查询结果?我可以做两个查询,但我很好奇Sequelize是否提供了这个?例如Playlist和PlaylistEntry:

    Playlist: sequelize.define('playlist', {
        name: Sequelize.STRING,
        description: Sequelize.STRING
    }),     

    PlaylistEntry: sequelize.define('playlist_entry', {
        playlist: Sequelize.INTEGER
        //track: Sequelize.INTEGER
    })

    PlaylistEntry.belongsTo(
     Playlist,
     { as: 'Playlist', foreignKey: { name: 'fk_playlist' }});

我希望(伪代码):

查询:

Playlist.find(where: {id: playlistId}, nestedResult: true);

结果:

[{
   id: 123,
   name: 'abc'
   playlistEntries: [{
      id: 321,
      track: 431
   }]
}]

1 个答案:

答案 0 :(得分:3)

Playlist.find({
  where: {}, 
  include: [
    {model: PlaylistEntry} //this should be PlaylistEntry model
  ]
})

http://docs.sequelizejs.com/en/latest/docs/models-usage/#eager-loading