Creatigng new using many to many in sequelize
In Sequelize, when creating a new record that involves a many-to-many relationship, you need to create the intermediate table record first, and then associate the two main table records with it.
Here's an example:
Let's say you have three tables: Users
, Roles
, and UserRoles
(the intermediate table).
Users table
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING
}
});
return User;
};
Roles table
module.exports = (sequelize, DataTypes) => {
const Role = sequelize.define('Role', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING
}
});
return Role;
};
UserRoles table (intermediate table)
module.exports = (sequelize, DataTypes) => {
const UserRole = sequelize.define('UserRole', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
}
});
return UserRole;
};
Now, let's create a new user and associate them with a role using the UserRoles
table.
Create a new user
const user = await User.create({
name: 'John Doe'
});
Create a new role
const role = await Role.create({
name: 'Admin'
});
Associate the user with the role
const userRole = await UserRole.create({
userId: user.id,
roleId: role.id
});
In this example, we first create a new user and a new role. Then, we create a new record in the UserRoles
table, associating the user with the role.
To retrieve the associated roles for a user, you can use the getRoles
method:
const user = await User.findByPk(1);
const roles = await user.getRoles();
console.log(roles); // Output: [{ id: 1, name: 'Admin' }]
Similarly, to retrieve the associated users for a role, you can use the getUsers
method:
const role = await Role.findByPk(1);
const users = await role.getUsers();
console.log(users); // Output: [{ id: 1, name: 'John Doe' }]
Note that in Sequelize, you need to define the associations between the tables using the belongsTo
and hasMany
methods. For example:
User.belongsToMany(Role, { through: 'UserRoles' });
Role.belongsToMany(User, { through: 'UserRoles' });
This defines the many-to-many relationship between Users
and Roles
through the UserRoles
table.