Sample Header Ad - 728x90

Defining hasMany self-associations in sequelize v7

0 votes
1 answer
28 views
export default class Folder extends Model, InferCreationAttributes> {
  
  @Attribute(DataTypes.INTEGER)
  @PrimaryKey
  @AutoIncrement
  declare id: CreationOptional;

  @Attribute(DataTypes.STRING)
  @NotNull
  declare title: string;

  @Attribute(DataTypes.INTEGER)
  declare parentId: number;

  declare parent?: NonAttribute;
  declare children?: NonAttribute;

  @HasMany(() => Folder, {
    // as: 'children',
    foreignKey: 'parentId',
    inverse: {
      as: 'parent'
    },
  })
For the HasMany association, if I don't include as: 'children' property, I get the following errors from sequelize : - SequelizeAssociationError: Defining HasMany association "parent" from _Folder to _Folder failed - Caused by: SequelizeAssociationError: Both options "as" and "inverse.as" must be defined for hasMany self-associations, and their value must be different. However, if I include the as: 'children' property, I get the following errors from typescript & sequelize : - Object literal may only specify known properties, and 'as' does not exist in type 'Omit, "as">'.ts(2353) - Error: The "as" option is not allowed when using association decorators. The name of the decorated field is used as the association name. How do I resolve this & get the self-association to work ?
Asked by Narayan Waraich (1 rep)
Jul 10, 2024, 12:44 AM
Last activity: Jan 3, 2025, 04:27 PM