Home > Mobile >  Sequelize findAll users with Id but return users from different column
Sequelize findAll users with Id but return users from different column

Time:04-26

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'],
          ],
        }]
      })
    },

CodePudding user response:

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)
    },
  • Related