Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize add association

Tags:

sequelize.js

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?

like image 708
Mark Robson Avatar asked Sep 16 '13 12:09

Mark Robson


1 Answers

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/

like image 113
Jan Aagaard Meier Avatar answered Oct 26 '22 06:10

Jan Aagaard Meier