Andre M
Andre M

Reputation: 7534

Sequelize and nested results?

Sequelize allows for data relationships, but I can't seem to see if there is a way to have it return a query result composed of the relation? I could do this as two queries, but I am curious as to whether Sequelize provides for this? For example Playlist and 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' }});

What I would be hoping for (pseudocode):

Query:

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

Result:

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

Upvotes: 1

Views: 423

Answers (1)

yBrodsky
yBrodsky

Reputation: 5041

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

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

Upvotes: 3

Related Questions