-
Notifications
You must be signed in to change notification settings - Fork 190
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How define belongsToMany association for users? #49
Comments
This is more an Sequelize question: https://sequelize.org/master/class/lib/associations/base.js~Association.html But I'll give you a quick example... // a team can have multiple members
Team.belongsToMany(User, {
as: 'teamMember', // this is how you can add, set or remove associations
through: 'team_members', // define the table, I would suggest to call it model1_model2 or if you have a different name for it then use the name as here model1_name
foreignKey: 'memberId',// I would always suggest to set your own if you want to work with the plain database
});
// a member can join multiple teams
User.belongsToMany(Team, {
as: 'membersTeam',
through: 'team_members',
foreignKey: 'teamId',
});
// use
const someUser = User.findByPk(1);
Team.addTeamMember(someUser);
Team.addTeamMember(2);
Team.addTeamMember(3);
// team has 1,2,3
Team.removeTeamMember(3);
// team has now member 1,2
Team.setTeamMember([4,5,6])
// team has now 4,5,6 and deletes other associations |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
I tried to make two models of User(exist in this repo) and Team(new).
I added following in User model.
const Team = require("./Team");
Team.memberAssociation = User.belongsToMany(Team, { through: "member" });
How do I make this relationship in Team model, and how to add a user to Team in UserController.js in a method like register?
The text was updated successfully, but these errors were encountered: