我有三个表: videoclips , 播放列表 和 videoclipPlaylistMap 。
我想返回一个包含所有播放列表的 JSON,并为每个播放列表返回一个包含视频剪辑的数组。
我无法弄清楚如何进行 Sequelize 关联以实现这一目标。
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
最佳答案
您需要告诉 Sequelize 使用 videoId 字段作为关系的目标键。默认情况下,在belongsTo 关联中,模型的主键用作目标键。您需要在关联中使用 targetKey 选项。
VideoclipPlaylistMap.belongsTo(Videoclip, { foreignKey: 'videoclipId', targetKey: 'videoId' });
http://docs.sequelizejs.com/manual/tutorial/associations.html#target-keys