1
votes

I set up two models in sequelize that have a many-to-many relationship. Sequelize created the join table correctly, but I'm not able to insert into it. I've been poring over this section of the docs: http://docs.sequelizejs.com/en/latest/docs/associations/#creating-with-associations but I can't get anything to work based on their examples. They don't have a many-to-many example, unfortunately.

Models Relationships :

db.user.hasMany(db.post, {through: "likes"});
db.post.belongsTo(db.user, {through: "likes"});
Post.findById(postId).then( (post) => {
        try{
            Post.setLikes({userId: 1, postId: 1});
        }catch(e){
            console.error(e);
        }
    });
1

1 Answers

1
votes

For many to many relationship you must use belongsToMany and not hasMany

in your case :

db.user.belongsToMany(db.post, {through: "likes"});
db.post.belongsToMany(db.user, {through: "likes"});

and you can use 3 methodes for manage this relationship add, remove and set

add and remove add or remove id(s) pass in parameter and set replace all ids in relationship by id(s) pass in parameter (set is a remove all + add id pass in parameter)

for exemple:

const postId = 1

Post.findById(postId).then( async(post) => {
        try{
            await Post.addLikes([1,2,3]); // 3 relationship are in db postId: 1 with userId: 1,2,3 
            await Post.removeLikes(1); // 2 relationship are in db postId: 1 with userId: 2,3  
            await Post.setLikes(1); // unique relationship is in db postId: 1 with userId:1
        }catch(e){
            console.error(e);
        }
    });

you can have more information here https://sequelize.org/master/class/lib/associations/has-many.js~HasMany.html#instance-method-add