Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda