我有三个表:视频片段,播放列表和 videoclipPlaylistMap 。
我想返回一个包含所有播放列表的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.videoclip
。id
应该转到videoclipPlaylistMaps.videoclip
。videoId
答案 0 :(得分:1)
您需要告诉Sequelize使用videoId字段作为关系的目标键。默认情况下,在belongsTo关联中,模型的主键用作目标键。您需要在关联中使用targetKey选项。
VideoclipPlaylistMap.belongsTo(Videoclip, { foreignKey: 'videoclipId', targetKey: 'videoId' });
http://docs.sequelizejs.com/manual/tutorial/associations.html#target-keys