1

Currently making a sns project. Have a user model and made a N:M association which tells you who is following who. So there is a connected models between 'user' and 'user'.

This is how my code looks like

static associate(db) {
    db.User.hasMany(db.Post);
    db.User.belongsToMany(db.User, {
      foreignKey: 'followingId',
      as: 'Followers',
      through: 'Follow',
    });
    db.User.belongsToMany(db.User, {
      foreignKey: 'followerId',
      as: 'Followings',
      through: 'Follow',
    });
  }

and I'm trying to show how many followers and following the user has at the profile page. So what I did is when the /main pass

const User = require('../models/user');

router.use((req, res, next) => {
  res.locals.followingList = User.findAll({
    where : {followerId : req.user}
  });
  next();
});

Having a problem accessing the data from through table.

Having a problem accessing the data from through table.

1 Answer 1

0

If we want to get the user along with followings and followers then you need to use findOne (or findByPk if req.user is a primary key value) because we want a single user and just include both associations in the query though I don't recommend to include more than one M:N associations to the same query:

 res.locals.followingList = await User.findOne({
    where : {id : req.user},
    include: [{
      model: User,
      as: 'Followers'
    }, {
      model: User,
      as: 'Followings'
    }]
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.