Class BelongsToManyAssociation<SourceModel, TargetModel, ThroughModel, SourceKey, TargetKey>

Many-to-many association with a join/through table. See Model.belongsToMany

When the join table has additional attributes, these can be passed in the options object:

UserProject = sequelize.define('user_project', {
role: DataTypes.STRING
});
User.belongsToMany(Project, { through: UserProject });
Project.belongsToMany(User, { through: UserProject });
// through is required!

user.addProject(project, { through: { role: 'manager' }});

All methods allow you to pass either a persisted instance, its primary key, or a mixture:

const project = await Project.create({ id: 11 });
await user.addProjects([project, 12]);

If you want to set several target instances, but with different attributes you have to set the attributes on the instance, using a property with the name of the through model:

p1.UserProjects = {
started: true
}
user.setProjects([p1, p2], { through: { started: false }}) // The default value is false, but p1 overrides that.

Similarly, when fetching through a join table with custom attributes, these attributes will be available as an object with the name of the through model.

const projects = await user.getProjects();
const p1 = projects[0];
p1.UserProjects.started // Is this project started yet?

In the API reference below, add the name of the association to the method, e.g. for User.belongsToMany(Project) the getter will be user.getProjects().

Type Parameters

Hierarchy (view full)

Constructors

Properties

fromSourceToThrough: HasManyAssociation<SourceModel, ThroughModel, SourceKey, any, any>
fromSourceToThroughOne: HasOneAssociation<SourceModel, ThroughModel, SourceKey, any, any>
isAliased: boolean
isSelfAssociation: boolean

The corresponding association this entity is paired with.

parentAssociation: null | Association<Model<any, any>, Model<any, any>, string, NormalizedAssociationOptions<string>>

A reference to the association that created this one.

Accessors

  • get associationType(): string
  • The type of the association. One of HasMany, BelongsTo, HasOne, BelongsToMany

    Returns string

  • get name(): {
        plural: string;
        singular: string;
    }
  • Returns {
        plural: string;
        singular: string;
    }

    • plural: string
    • singular: string
  • get otherKey(): string
  • The name of the Foreign Key attribute, located on the through table, that points to the Target model.

    Not to be confused with

    Returns string

    Link

    , which points to the Source model instead.

Methods