I have two tables: Books and Articles with a many-to-many relationship between them. Joining table is BookArticles.
models/books.js
module.exports =
This is how i solved the similar problem i had two models a user model
var user = sequelize.define('user', {
name: {
Sequelize.STRING(255)
},
email: {
type: Sequelize.STRING(255),
unique: true,
validate: {
isEmail: true
}
}
});
and a roles model
var Role = sequelize.define('role', {
name: {
Sequelize.ENUM('ER', 'ALL', 'DL')
},
description: {
type: Sequelize.TEXT
}
});
Then i created the union model UserRole
var UserRole = sequelize.define('user_role', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.ENUM('Admin', 'Staff', 'Customer', 'Owner')
}
});
Note: you have to explicitly define the id for UserRole otherwise sequelize will use the two foreign keys in this case user_id
and role_id
as your primary keys.
Then i created the belongs to many relationship as follows
User.belongsToMany(Role, { as: 'Roles', through: { model: UserRole, unique: false }, foreignKey: 'user_id' });
Role.belongsToMany(User, { as: 'Users', through: { model: UserRole, unique: false }, foreignKey: 'role_id' });