Association Basics
Sequelize provides what are called associations. These can be declared on your models to define common relationships between your tables.
The two concepts are closely related, but not the same. Associations are defined in JavaScript between your models, while relationships are defined in your database between your tables.
Sequelize supports the standard associations: One-To-One, One-To-Many and Many-To-Many.
One-to-one Relationships
In a One-To-One relationship, a row of one table is associated with a single row of another table.
The most common type of One-To-One relationship is one where one side is mandatory, and the other side is optional. For instance, a driving license always belongs to a single person, but a person can have zero or one driving licenses (from the same place).
One-To-One relationships can be created by using the HasOne
association.
One-to-many Relationships
In a One-To-Many relationship, a row of one table is associated with zero, one or more rows of another table.
For instance, a person is always born in one city, but a city can have zero or more people born in it.
One-To-Many relationships can be created by using the HasMany
association.
Many-to-many Relationships
In a Many-To-Many relationship, a row of one table is associated with zero, one or more rows of another table, and vice versa.
For instance, a person can have liked zero or more Toots, and a Toot can have been liked by zero or more people.
Many-To-Many relationships can be created by using the BelongsToMany
association.