Premium lesson

Defining Relationships in Sequelize

Sequelize·3 min read·Jan 1, 2025

In Sequelize, the definition of a relationship between models allows you to represent the associations between their underlying SQL tables and facilitate the querying and management of related data, much like foreign keys and joins.

These relationships are established through the use of built-in model methods, including hasOne, belongsTo, hasMany, and belongsToMany.

These methods are usually declared in pair and allow you to create three primary types of relationships:

  • One-to-one relationships using the association of hasOne and belongsTo.

  • One-to-many relationships using the association of hasMany and belongsTo.

  • Many-to-many relationships using the association of two belongsToMany (not covered in this lesson).

Defining one-to-one relationships

In a one-to-one relationship, each record in the first table is associated with exactly one record in the second table through the use of a foreign key.

To create a one-to-one relationship between two models, you can use the hasOne and belongsTo methods of the model instances:

Source.hasOne(Target);Target.belongsTo(Source);
icon light bulb key

Unlock the Build RESTful APIs in Node.js module

Learn how to build real database-backed and framework-powered RESTful APIs with MySQL, Sequelize, and Express.

You get immediate access to:

  • 37 focused lessons across MySQL, Sequelize, backend, and Express
  • 4 real-world projects with commented solutions
  • Ongoing updates to this bundle
  • Lifetime access to this bundle
Unlock this module