You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Sequelize中查询用户收藏的帖子而非发布的帖子

查询Sequelize多对多关联的收藏帖子并移除中间表字段

问题背景

已定义User和Post模型的两种关联:一对多的发布关系,以及多对多的收藏关系。使用getBookmarkedPosts()查询收藏帖子时,即便设置了through.attributes: [],结果仍包含user_bookmark关联表的字段。

解决方案

方案1:优化getBookmarkedPosts()查询参数

如果需要保留模型实例,可手动清理返回结果;或者添加raw: true直接返回纯数据对象:

// 方式1:手动移除中间表字段
let posts = await user.getBookmarkedPosts({
  where: { is_active: true },
  attributes: ['id', 'image', 'name'],
  through: { attributes: [] }
});
posts = posts.map(post => {
  delete post.User_Bookmarks;
  return post;
});

// 方式2:返回纯JSON对象(无需模型实例)
let posts = await user.getBookmarkedPosts({
  where: { is_active: true },
  attributes: ['id', 'image', 'name'],
  through: { attributes: [] },
  raw: true
});

方案2:使用include关联查询

通过User.findByPk配合include查询,这种方式更灵活,能直接排除中间表字段:

const user = await User.findByPk(req.user.id, {
  include: [
    {
      model: Post,
      as: 'BookmarkedPosts', // 必须与关联定义的别名一致
      where: { is_active: true },
      attributes: ['id', 'image', 'name'],
      through: { attributes: [] } // 彻底排除中间表字段
    }
  ]
});
const bookmarkedPosts = user.BookmarkedPosts;

原理说明

Sequelize的多对多关联查询中,生成的getXxx()方法默认会携带关联表的元数据字段。通过through.attributes: []可以在查询层面排除这些字段,但模型实例可能仍会保留关联属性,此时手动删除或使用raw: true即可得到纯帖子数据。而include方式则直接在查询构建阶段过滤掉中间表字段,结果更纯净。

内容的提问来源于stack exchange,提问作者Abolfazl Mashhadi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 04:27:39