Documentation
    Preparing search index...

    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

    Index
    fromSourceToThrough: HasManyAssociation<
        SourceModel,
        ThroughModel,
        SourceKey,
        any,
    >
    fromSourceToThroughOne: HasOneAssociation<
        SourceModel,
        ThroughModel,
        SourceKey,
        any,
    >
    isAliased: boolean
    isSelfAssociation: boolean
    pairedWith: BelongsToManyAssociation<
        TargetModel,
        SourceModel,
        ThroughModel,
        TargetKey,
        SourceKey,
    >

    The corresponding association this entity is paired with.

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

    A reference to the association that created this one.

    • get associationType(): string

      The type of the association. One of HasMany, BelongsTo, HasOne, BelongsToMany

      Returns string