Mark Robson
Mark Robson

Reputation: 1328

Sequelize add association

I have an association set up like this:

m.User.hasMany(m.Interests, { joinTableName: 'user_interests', foreignKey: 'user_id' });
m.Interests.hasMany(m.User, { joinTableName: 'user_interests', foreignKey: 'interest_id' });

Sequelize is awesome in that I can just do user.getInterests. But how can I add a new association?

Upvotes: 11

Views: 12402

Answers (1)

Jan Aagaard Meier
Jan Aagaard Meier

Reputation: 28778

You can do either:

user.addInterest(interest)

To add a new interest, without changing the current ones, or you can do:

user.setInterests([interest])

The second option means associate only the interest I just gave you with the user, and remove any old associations if they exist.

https://sequelize.readthedocs.io/en/v3/docs/associations/

Upvotes: 18

Related Questions