Define Relationships Between Tables in Sequelize

Sequelize·2 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).

Define 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);

Where:

  • Source is the model instance containing the primary key.
  • Target is the model instance containing the foreign key.

Unlock the program 🚀

Pay once, own it forever.

€79

30-day money-back guarantee

  • 13 modules
  • 113 lessons with full-code examples
  • 29 projects with commented solutions
  • All future lesson and project updates
  • Lifetime access

By submitting this form, you agree to the Terms & Conditions and Privacy Policy.