Associations
belongsTo, hasOne, hasMany and belongsToMany work as in Sequelize v6, including aliases, custom keys, junction models, eager loading with include, accessor methods and nested creation.
Defining associations
class Author extends Model<InferAttributes<Author>, InferCreationAttributes<Author>> {
declare id: CreationOptional<number>;
declare name: string;
declare posts?: NonAttribute<Post[]>;
declare getPosts: (options?: FindOptions) => Promise<Post[]>;
declare countPosts: (options?: FindOptions) => Promise<number>;
declare createPost: (values: Partial<InferCreationAttributes<Post>>) => Promise<Post>;
}
class Post extends Model<InferAttributes<Post>, InferCreationAttributes<Post>> {
declare id: CreationOptional<number>;
declare title: string;
declare authorId: ForeignKey<number>;
declare author?: NonAttribute<Author>;
declare tags?: NonAttribute<Tag[]>;
declare addTags: (tags: Tag[]) => Promise<void>;
}
class Tag extends Model<InferAttributes<Tag>, InferCreationAttributes<Tag>> {
declare id: CreationOptional<number>;
declare label: string;
}
Author.init(
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
name: { type: DataTypes.TEXT, allowNull: false },
},
{ sequelize },
);
Post.init(
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
title: { type: DataTypes.TEXT, allowNull: false },
},
{ sequelize },
);
Tag.init(
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
label: { type: DataTypes.TEXT, allowNull: false },
},
{ sequelize },
);
Author.hasMany(Post, { as: 'posts', foreignKey: 'authorId' });
Post.belongsTo(Author, { as: 'author', foreignKey: 'authorId' });
Post.belongsToMany(Tag, { as: 'tags', through: 'PostTags' });
Tag.belongsToMany(Post, { as: 'posts', through: 'PostTags' });
await sequelize.sync();Notes on the example:
asnames the association. It is the key of the loaded value (author.posts) and the base of the accessor names (getPosts,countPosts,createPost).foreignKeysets the foreign key attribute; without it, v6 naming applies (AuthorIdforAuthor.hasMany(Post)).through: 'PostTags'creates the junction model automatically. Pass a model to add your own columns to the junction table.ForeignKey<number>andNonAttribute<...>keep these fields out of the creation attributes.- The accessor methods exist at runtime; declare the ones you use with
declareso TypeScript knows them. postgrelize does not export the v6HasManyGetAssociationsMixin-style helper types, so write the signatures directly.
sync() creates the foreign key constraints with the v6 defaults: ON DELETE SET NULL for nullable foreign keys (NO ACTION for allowNull: false), ON DELETE CASCADE for junction tables, and ON UPDATE CASCADE. Override them with onDelete / onUpdate, or skip constraints with constraints: false.
Default aliases and foreign keys come from the model's name init option when it is set (name: { singular: 'user', plural: 'users' }, as in v6), otherwise from the inflected modelName. An include entry takes a custom join condition with on; it replaces the key condition of belongsTo, hasOne and hasMany includes (not of belongsToMany).
Nested creation
create, build and bulkCreate accept nested values for associations listed in include. postgrelize inserts the parent, then the children with the foreign keys set:
// Nested values are not creation attributes: pass them as a variable, not an object literal.
const values = { name: 'Ann', posts: [{ title: 'Hello' }, { title: 'PostgreSQL tips' }] };
const ann = await Author.create(values, { include: [{ association: 'posts' }] });Nested creation works for all four association types and for multiple levels (include: [{ association: 'posts', include: ['comments'] }]). For belongsToMany, the junction row can carry values: { label: 'admin', UserRoles: { level: 'high' } }.
Accessors
Instances get the v6 accessor methods:
| Association | Methods |
|---|---|
belongsTo, hasOne | get<Name>, set<Name>, create<Name> |
hasMany, belongsToMany | get<Names>, count<Names>, has<Name> / has<Names>, set<Names>, add<Name> / add<Names>, remove<Name> / remove<Names>, create<Name> |
const sql = await Tag.create({ label: 'sql' });
const [tips] = await ann.getPosts({ where: { title: { [Op.like]: '%tips' } } });
await tips?.addTags([sql]);
await ann.createPost({ title: 'Drafts' });
const postCount = await ann.countPosts();get<Names> and count<Names> take find options (where, order, limit, transaction, ...). Return values follow v6:
hasOneset<Name>accepts an instance, a primary key (a stub is built from the key, no lookup) ornull. It resolves to the saved instance, or tonullwhen the instance is already linked or the association is cleared.belongsToset<Name>(value, { save: false })only sets the foreign key and resolves toundefined.belongsToManyget<Names>attaches the junction row under the junction model name.joinTableAttributespicks its columns ([]omits it); withraw: truethe rows are flat and carryJunction.columnkeys.- Including a model with an unknown
as, or a model associated several times withoutas, rejects withEagerLoadingError.
Eager loading
include loads associations in the same query with LEFT OUTER JOIN (or INNER JOIN with required: true, which is implied when the include has a where):
const authors = await Author.findAll({
include: [
{
association: 'posts',
required: true,
include: [{ association: 'tags', where: { label: 'sql' }, through: { attributes: [] } }],
},
],
});
const withAuthor = await Post.findAll({
include: [{ association: 'author', attributes: ['name'] }],
order: [['id', 'ASC']],
});
const separate = await Author.findAll({
include: [{ association: 'posts', separate: true, order: [['title', 'ASC']] }],
});Include options follow v6: association or model + as, where, required, right, attributes, nested include, paranoid, through: { attributes, where } for belongsToMany, and all: true.
limitwith multi-row includes. As in v6, alimiton the main query together with ahasMany/belongsToManyinclude moves the main table into a subquery, so the limit counts parent rows.subQuery: falseturns this off.separate: true(hasMany only) loads the association with a second query instead of a join, with its ownorderandlimit(applied per parent, as in Sequelize v6). This avoids row multiplication when a parent has many children.$nested.attr$keys in the top-levelwherefilter on included columns, as in v6.minifyAliases: true(constructor option, as in v6) shortens the aliases of included columns (Posts.Comments.titlebecomes_0) and of table aliases of 64 or more characters, then maps the rows back. PostgreSQL identifiers hold 63 bytes: without the option a deeply nested include with long association names gets truncated column aliases that can collide, and attributes go missing. It is off by default and applies to the joined include query offindAll,findOne,findByPkandfindAndCountAll;separateincludes run their own query with their own aliases. SQL logs show the short names. Unlike v6, aliases of attributes you rename yourself (attributes: [[fn(...), 'total']]) are left as written.
Counting with includes: count({ include }) counts joined rows, as in v6; add distinct: true to count parent rows.
Differences from Sequelize v6
Associations behave like v6, including default scopes of included models (a scoped include with a where becomes required) and Model.unscoped() or Model.scope(...) passed as the include model. Three v6 bugs are fixed (see Sequelize issues fixed):
belongsToManywith a customsourceKeyandlimitreturns the right rows.- A top-level
$include.attr$condition with ahasManyinclude andlimitproduces valid SQL: the limit subquery is turned off, solimitcounts joined rows. - Nested
createwith a built instance as a child (Post.create({ Comments: [Comment.build(...)] }, { include: [Comment] })) saves and links the instance; v6 silently drops it.
API reference
Model—belongsTo,hasOne,hasMany,belongsToManyAssociationOptions,BelongsToManyOptionsIncludeOptions