I created a many-to-many association between courses and users like this:
Course.belongsToMany(User, { through: 'CourseUser'});
User.belongsToMany(Course, { through: 'CourseUser'});
which generates a join table called CourseUser.
I add a relation for a specific course and user with the following server side function that happens on the click of a button: the userCourse variable looks like this: { UserId: 7, CourseId: 13 }
addUser: function(req, res) {
var userCourse = req.body;
db.CourseUser.create(userCourse).then(function () {
res.sendStatus(200);
});
}
Is this the correct way of adding the association between an existing user and an existing course? (if not, what is the correct way)
I would like to have an ability of removing the association when clicking on another button. But I can't quite figure out how to set up the function.
To delete rows of data from your SQL table using Sequelize, you need to use the provided destroy() method. The destroy() method can be called from any Model or instance of your Model to delete rows from your table.
Closing the connection If you need to close the connection, call sequelize.close() (which is asynchronous and returns a Promise). Once sequelize.close() has been called, it's impossible to open a new connection. You will need to create a new Sequelize instance to access your database again.
Creating the standard relationships To create a One-To-One relationship, the hasOne and belongsTo associations are used together; To create a One-To-Many relationship, the hasMany and belongsTo associations are used together; To create a Many-To-Many relationship, two belongsToMany calls are used together.
User
and Course
instance and are just associating them in addUser
, then yes, this is the correct way of creating an association between them.1: Through User
model:
User.removeCourse(courseObject);
2: Through Course
model:
Course.removeUser(userObject);
3: On the CourseUser
model, without having a CourseUser
instance available:
db.CourseUser.destroy({
where: {...}
});
4: Having a CourseUser
instance available:
courseUser.destroy();
You can bind .then
and .catch
on all these operations to do something on success / on error.
Your model relationship is okay:
Course.belongsToMany(User, { through: 'CourseUser'}); User.belongsToMany(Course, { through: 'CourseUser'});
and values: { UserId: 7, CourseId: 13 }
Implementation could look thus for adding a UserCourse relationship:
addUser: function(req, res) {
const { UserId, CourseId } = req.body;
db.Course.findOne({
where: { id: CourseId }
}).then(course => {
course.setUsers([UserId])
res.sendStatus(200);
}).catch(e => console.log(e));
}
removeUser: function (req, res) {
const { UserId, CourseId } = req.body;
db.Course.findOne({
where: { id: CourseId }
}).then(course => {
course.removeUsers([UserId])
res.sendStatus(200);
}).catch(e => console.log(e));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With