Sequelize Associations

Last modified: May 05, 2022

Associations/Relationship

  • one to one
  • one to many
  • many to many

- one to one

db.person.hasOne(db.user); db.user.belongsTo(db.person);

- one to many

db.user.hasMany(db.profile); db.profile.belongsTo(db.user);

- Many to Many

//we create a junction model to link between Roles and User model/table const UserRole = sequelize.define('UserRoles', { id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false }, }, { timestamps: false }); db.role.belongsToMany(db.user, { through: UserRole }); // a role belongs to many user and a user has mnay roles so it is M:M db.user.belongsToMany(db.role, { through: UserRole });

Complete Code

const config = require('../../config/config'); const Sequelize = require("sequelize"); const sequelize = new Sequelize( config.development ) const db = {}; db.Sequelize = Sequelize; db.sequelize = sequelize; db.user = require('./user')(sequelize, Sequelize); db.role = require('./role')(sequelize, Sequelize); db.person = require('./person')(sequelize, Sequelize); db.profile = require('./profile')(sequelize, Sequelize); db.movie = require('./movie')(sequelize, Sequelize); const UserRole = sequelize.define('UserRoles', { id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false }, }, { timestamps: false }); db.userrole = UserRole; db.role.belongsToMany(db.user, { through: UserRole }); db.user.belongsToMany(db.role, { through: UserRole }); db.person.hasOne(db.user); db.user.belongsTo(db.person); db.user.hasMany(db.profile); db.profile.belongsTo(db.user); db.ROLES = ["user", "admin"]; module.exports = db;