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

133
Views
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 answers
Answer question

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 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!