Complete Explanation of Database Model Relationships in Sequelize

 


Sequelize is an Object-Relational Mapping (ORM) for Node.js used to interact with SQL databases such as MySQL, PostgreSQL, SQLite, and MSSQL. One of Sequelize’s essential features is its ability to define relationships between models.

1. Types of Relationships in Sequelize

Sequelize supports several types of relationships:

  1. One-to-One (1:1) → One entity is related to only one other entity.
  2. One-to-Many (1:M) → One entity can have multiple related entities.
  3. Many-to-Many (M:N) → Many entities are related to many other entities.

2. Implementing Relationships in Sequelize

a) One-to-One Relationship

In a 1:1 relationship, one row in table A is linked to only one row in table B.

Example Scenario

Let's say we have two tables:

  • User (Stores user information)
  • Profile (Stores additional user details)

Implementation in Sequelize

const { Sequelize, DataTypes } = require("sequelize");
const sequelize = new Sequelize("database", "username", "password", {
  dialect: "mysql",
});

// Define Models
const User = sequelize.define("User", {
  name: { type: DataTypes.STRING, allowNull: false },
});

const Profile = sequelize.define("Profile", {
  bio: { type: DataTypes.STRING },
});

// One-to-One Relationship
User.hasOne(Profile, {
  foreignKey: "userId",
  as: "profile",
});
Profile.belongsTo(User, {
  foreignKey: "userId",
  as: "user",
});

// Sync Database
sequelize.sync({ force: true }).then(() => console.log("Database synced"));

Explanation

  • User.hasOne(Profile) → Indicates that one user has only one profile.
  • Profile.belongsTo(User) → Indicates that a profile belongs to one specific user.
  • foreignKey: "userId" → Defines the foreign key (userId) in the Profile table.

b) One-to-Many Relationship

In a 1:M relationship, one entity in table A can have multiple entities in table B.

Example Scenario

We have two tables:

  • User (Application users)
  • Post (Posts created by users)

Implementation in Sequelize

const Post = sequelize.define("Post", {
  title: { type: DataTypes.STRING, allowNull: false },
  content: { type: DataTypes.TEXT },
});

// One-to-Many Relationship
User.hasMany(Post, {
  foreignKey: "userId",
  as: "posts",
});
Post.belongsTo(User, {
  foreignKey: "userId",
  as: "author",
});

Explanation

  • User.hasMany(Post) → Indicates that one user can have multiple posts.
  • Post.belongsTo(User) → Indicates that each post belongs to one user.
  • foreignKey: "userId" → Adds the userId column in the Post table to link it to User.

c) Many-to-Many Relationship

In a M:N relationship, many entities in table A can be related to many entities in table B.

Example Scenario

We have two tables:

  • Student (Students)
  • Course (Courses)

Since one student can enroll in multiple courses, and one course can have multiple students, we need an intermediate table.

Implementation in Sequelize

const Student = sequelize.define("Student", {
  name: { type: DataTypes.STRING, allowNull: false },
});

const Course = sequelize.define("Course", {
  title: { type: DataTypes.STRING, allowNull: false },
});

// Many-to-Many Relationship
Student.belongsToMany(Course, { through: "StudentCourses" });
Course.belongsToMany(Student, { through: "StudentCourses" });

Explanation

  • Student.belongsToMany(Course, { through: "StudentCourses" }) → Sequelize will create an intermediate table (StudentCourses).
  • Course.belongsToMany(Student, { through: "StudentCourses" }) → A two-way relationship where a student can have many courses, and a course can have many students.

3. Using Relationships in Queries

Once relationships are defined, they can be used in queries with Sequelize.

a) Fetching Data with Relationships (Include)

const getUsersWithProfile = async () => {
  const users = await User.findAll({
    include: [{ model: Profile, as: "profile" }],
  });
  console.log(JSON.stringify(users, null, 2));
};
getUsersWithProfile();

b) Saving Data with Relationships

const createUserWithProfile = async () => {
  const user = await User.create(
    {
      name: "John Doe",
      profile: { bio: "Web Developer" },
    },
    { include: [{ model: Profile, as: "profile" }] }
  );
  console.log("User Created:", user.toJSON());
};
createUserWithProfile();

Conclusion

  • One-to-One (hasOne - belongsTo) → Example: User & Profile
  • One-to-Many (hasMany - belongsTo) → Example: User & Post
  • Many-to-Many (belongsToMany - belongsToMany) → Example: Student & Course
  • Use include in queries to fetch related data.

By understanding these concepts, you can build more complex database-driven applications using Sequelize! 

Post a Comment

0 Comments