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 :)
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.