Sequelize多表关联查询:获取用户喜爱标签关联的无重复帖子
使用Sequelize查询用户喜爱标签关联的无重复帖子
前提准备:确保模型关联已正确定义
假设你的模型分别为:User、UserFavoriteTag(用户喜爱标签表)、Tag、PostTag(帖子标签表)、Post,需要先建立以下关联:
User.hasMany(UserFavoriteTag, { foreignKey: 'user_id' })UserFavoriteTag.belongsTo(Tag, { foreignKey: 'tag_id' })Tag.hasMany(PostTag, { foreignKey: 'tag_id' })PostTag.belongsTo(Post, { foreignKey: 'post_id' })
实现方式一:分步查询
先获取目标用户喜爱的所有标签ID,再通过这些ID查询关联的无重复帖子:
// 1. 获取用户喜爱的标签ID列表 const favoriteTagIds = await UserFavoriteTag.findAll({ attributes: ['tag_id'], where: { user_id: 目标用户ID }, raw: true }).then(rows => rows.map(row => row.tag_id)); // 2. 查询关联的无重复帖子 const relatedPosts = await Post.findAll({ include: [{ model: PostTag, where: { tag_id: favoriteTagIds }, attributes: [] // 不需要返回PostTag的字段 }], distinct: true, // 去重 raw: true // 如果需要原始数据可选 });
实现方式二:关联查询一步完成
通过嵌套关联直接查询,同时利用distinct去重:
const relatedPosts = await Post.findAll({ include: [{ model: PostTag, include: [{ model: Tag, include: [{ model: UserFavoriteTag, where: { user_id: 目标用户ID }, attributes: [] }], attributes: [] }], attributes: [] }], distinct: true });
关键说明
- 使用
distinct: true确保返回的帖子没有重复项 - 嵌套关联时通过
attributes: []过滤不需要返回的中间表字段,精简结果 - 替换代码中的
目标用户ID为实际的用户ID值
内容的提问来源于stack exchange,提问作者mohammad reza shabani
相关产品推荐
相关产品推荐

