Many To Many Self Reference In Sequelize In Twitter Like Web-app
Solution 1:
When you create the M:M association you use as: 'Follower'
and as: 'Followed'
attributes. It influences the way you can add/set/delete associations between users. Method to add followed user to other user is now called addFollowed
and would be used in exactly the same way you did it.
User.findById(userId).then( currentUser => {
User.findById(followId).then( follows => {
currentUser.addFollowed(follows); // notice the difference here
});
});
The same occurs if you want to add follower to given user - then you would use addFollower
method.
Moreover, in your second solution you have made a mistake while creating the associating Model. In the User
model you have defined associations via foreign keys FollowerId
and FollowedId
, however in the FollowerFolloweds
definition you have created followerId
and followedId
, so those two do not match each other - you need to keep the names consistent.
EDIT
According to the documentation in the belongsToMany
relation, the as
attribute should be named as plural, so in your case you should name those as: 'Followers'
and as: 'Followeds'
(the second one seems a little strange). Sequelize singularizes those values itself, however you can define it by yourself using object as: { singular: 'Follower', plural: 'Followers' }
The alias of this association. If you provide a string, it should be plural, and will be singularized using node.inflection. If you want to control the singular version yourself, provide an object with plural and singular keys.
Post a Comment for "Many To Many Self Reference In Sequelize In Twitter Like Web-app"