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

如何用Sequelize仅获取当前用户关注对象的帖子

实现当前用户关注对象的帖子查询(Sequelize)

核心实现方案

基于你已配置的模型关联,可以通过关联查询直接获取当前用户关注对象发布的帖子,以下是具体代码:

方式一:关联链式查询(推荐)

const currentUserId = 1; // 替换为实际的当前用户ID

const followedPosts = await models.Post.findAll({
  include: [
    {
      model: models.User,
      as: 'User', // 若Post.belongsTo配置了自定义别名,需替换为对应值
      include: [
        {
          model: models.Follower,
          as: 'IsFollower',
          where: { FollowerId: currentUserId },
          required: true // 确保仅返回被当前用户关注的用户的帖子
        }
      ]
    }
  ],
  order: [['createdAt', 'DESC']] // 按发布时间倒序,可选
});

方式二:分步查询(灵活可控)

如果需要拆分逻辑或做额外处理,可以先获取关注列表,再查询对应帖子:

const currentUserId = 1;

// 第一步:获取当前用户关注的所有用户ID
const followings = await models.Follower.findAll({
  where: { FollowerId: currentUserId },
  attributes: ['FollowingId']
});
const followedUserIds = followings.map(item => item.FollowingId);

// 第二步:查询这些用户发布的帖子
const followedPosts = await models.Post.findAll({
  where: { UserId: followedUserIds },
  include: [{ model: models.User }], // 可选:同时返回帖子作者信息
  order: [['createdAt', 'DESC']]
});

关键说明

  1. 关联逻辑匹配:
    代码中IsFollower别名与你配置的models.User.hasMany(models.Follower, {foreignKey: "FollowerId", as: "IsFollower"})完全对应,确保关联关系生效。
  2. 数据筛选规则:
    required: true等价于SQL的INNER JOIN,只保留存在关注关系的用户帖子;若需要包含当前用户自己的帖子,可以在where中添加UserId: currentUserId或调整关联逻辑。
  3. 性能优化:
    关联查询减少了数据库请求次数,适合大多数场景;若关注用户量极大,分步查询可配合分页、批量查询进一步优化。

内容的提问来源于stack exchange,提问作者Harry Sayers

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:27:27