Next.js Discord

Discord Forum

Sequelize V7 belongToMany not work

Unanswered
Huyenlong posted this in #help-forum
Open in Discord
hi
I try to make a belongToMany association in sequelize V7.
I folowed this page : https://sequelize.org/docs/v7/associations/belongs-to-many/

This is my code :

export class Licence extends Model<InferAttributes<Licence>, InferCreationAttributes<Licence>> {
    @Attribute(DataTypes.INTEGER)
    @PrimaryKey
    @AutoIncrement
    declare id: CreationOptional<number>;

    @BelongsToMany(() => Season, {
        through: "LicenceSeason",
        inverse: {
          as: 'licence',
        },
      })
    declare licenceSeason?: NonAttribute<Season[]>;
    declare season?: NonAttribute<Season[]>;
}


import { Licence } from './Licence';

export class Season extends Model<InferAttributes<Season>, InferCreationAttributes<Season>> {

    @Attribute(DataTypes.INTEGER)
    @PrimaryKey
    @AutoIncrement
    declare id: CreationOptional<number>

    declare licence?: NonAttribute<Licence[]>

}


And this is the error :


[cause]: AssociationError [SequelizeAssociationError]: Association "season" needs to create the BelongsToMany association "licence" from Season to Licence, but it failed

.... (a lot of path)

[cause]: AssociationError [SequelizeAssociationError]: The association "licence" needs to define the HasOne association "licenceSeason" from Season to LicenceSeason,
but that child association has already been defined as HasMany, to LicenceSeason by this call:

Licence.belongsToMany(Season, {
through: { model: LicenceSeason },
inverse: { as: 'licence' },
as: 'season',
otherKey: {},
throughAssociations: {},
foreignKey: {},
hooks: false,
name: { plural: 'season', singular: 'season' }
})

That association would be re-used if compatible, but it is incompatible because their types are different (HasOne vs HasMany)

```

I do not understand where is my mistake

0 Replies