Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
How to only retrieve posts from other users the user is following using Sequelize

I'm trying to query my posts table to retrieve posts that the user follows. This is a popular pattern so I'm assuming there is a way to do it with Sequelize.

I have a User model which is associated to a Post model.

models.User.hasMany(models.Post, {constraints: false, foreignKey: "UserId", onDelete: 'cascade'});

models.Post.belongsTo(models.User, {foreignKey: "UserId", onDelete: 'cascade'})

The User model is associated to a Followers model (which shows User A follows User B)

models.User.hasMany(models.Follower, {foreignKey: "FollowerId", as: "IsFollower"});

models.Follower.belongsTo(models.User, {foreignKey: "FollowerId", as: "IsFollower"});

models.User.hasMany(models.Follower, {foreignKey: "FollowingId", as: "IsFollowing"});

models.Follower.belongsTo(models.User, {foreignKey: "FollowingId", as: "IsFollowing"});

Essentially I'm trying to search for posts where the user that created the post is followed by the user doing the query... like instagram, twitter etc where you only see posts of the people you follow.

Thanks in advance, Harry :)

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

Assuming these are your models using many to many relationship.

Follower Model:

module.exports = (sequelize, DataTypes) => {
  class Follower extends Model {
    static associate(models) {}
  };
  Follower.init({
    userId: DataTypes.INTEGER,
    followerId: DataTypes.INTEGER
  }, {
    sequelize,
    modelName: 'Follower',
    updatedAt: false
  });
  return Follower;
};

User Model:

  class User extends Model {
    static associate(models) {
      this.belongsToMany(models.User, { through: models.Follower, as: 'followers', foreignKey: 'userId', otherKey: 'followerId' });
    }
  };

You can fetch all the users a specific user follows by the following,

const userId = 1; // as an example
const followedUsers = await models.Follower.findMany({
    where: {
      followerId: userId
    }
});

To get posts whose owner is followed by user:

const posts = await models.Posts.findMany({
   where: {
      ["$author.followers.id$"]: userId
   }
});

Assuming Post model have one-to-many relationship with User named author.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!