Sequelize关联:在JSON响应中包含实体

时间:2017-12-26 17:26:27

标签: mysql json node.js sequelize.js

我有三个表:视频片段播放列表 videoclipPlaylistMap

  • Videoclips表有一个int id 作为主键, videoId 作为字符串。
  • VideoclipPlaylist地图将 playlistId 作为指向播放列表中的id的外键,将 videoclipId 作为指向 videoId的外键 来自videoclips表。

我想返回一个包含所有播放列表的JSON,并为每个播放列表返回一个包含视频片段的数组。

我无法弄清楚如何进行续集关联以实现这一目标。

let Videoclip = sequelize.define('videoclip',{
    title: Sequelize.STRING,
    videoId: Sequelize.STRING,
    thumbnail: Sequelize.STRING,
    channelTitle: Sequelize.STRING,
    duration: Sequelize.DOUBLE,
    viewCount: Sequelize.INTEGER
});

let Playlist = sequelize.define('playlist', {
    name: Sequelize.STRING,
    userId: Sequelize.INTEGER,
    tagList: Sequelize.STRING
});

let VideoclipPlaylistMap = sequelize.define('videoclipPlaylistMap', {
    videoclipId: Sequelize.STRING,
    playlistId: Sequelize.INTEGER
});

User.hasMany(Playlist, {foreignKey: 'userId'});
Playlist.belongsTo(User, {foreignKey: 'userId'});
Playlist.hasMany(VideoclipPlaylistMap, {foreignKey: 'playlistId'});
VideoclipPlaylistMap.belongsTo(Videoclip, {foreignKey: 'videoclipId'});

现在它正在执行此连接:

LEFT OUTER JOIN `videoclips` AS `videoclipPlaylistMaps.videoclip` ON `videoclipPlaylistMaps`.`videoclipId` = `videoclipPlaylistMaps.videoclip`.`id`

而不是videoclipPlaylistMaps.videoclipid应该转到videoclipPlaylistMaps.videoclipvideoId

1 个答案:

答案 0 :(得分:1)

您需要告诉Sequelize使用videoId字段作为关系的目标键。默认情况下,在belongsTo关联中,模型的主键用作目标键。您需要在关联中使用targetKey选项。

    VideoclipPlaylistMap.belongsTo(Videoclip, { foreignKey: 'videoclipId', targetKey: 'videoId' });

http://docs.sequelizejs.com/manual/tutorial/associations.html#target-keys