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

135
Visualizações
Sequelize findAll users with Id but return users from different column

I have a followers join table in my DB.

enter image description here

followedByUserId is the user that is the follower, followingUserId is the user they follow.

I am trying to write a sequelize query that finds all the entries in the followingUserId that are equal to an ID but returns the users that are sitting in the followedByUserId column. Can I achieve this?

QUERY

    getAllUserFollowing: (_, args) => {
      return DB.models.user.findAll({ // if args.id === 1, return user => 2
        include: [{
          model: DB.models.follower,
          where: {
            followingUserId: args.id, 
          },
          order: [
            ['createdAt', 'DESC'],
          ],
        }]
      })
    },
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you want to limit Follower records by a certain followingUserId value that means you want to get all followers of a certain user.
That means you just need to query all Follower records where followingUserId equals to a given user id and include followed users.
Assuming you have these associations:

Follower.belongsTo(User, { foreignKey: 'followingUserId', as: 'FollowingUser' });
Follower.belongsTo(User, { foreignKey: 'followedByUserId', as: 'FollowedByUser' });

you need a query like this:

getAllUserFollowing: async (_, args) => {
      return (await DB.models.Follower.findAll({ // if args.id === 1, return user => 2
        where: {
          followingUserId: args.id, 
        },
        include: [{
          model: DB.models.user,
          as: 'FollowedByUser',
        }],
        order: [
          ['FollowedByUser', 'createdAt', 'DESC'],
        ],
      })).map(x => x.FollowedByUser)
    },
about 4 years ago · Juan Pablo Isaza 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