How to define associations in Sequelize with typescript?

Viewed 10

I already tried other posts here but with no success.

I'm trying to define a N:N association between Category model ans Project model, through ProjectCategory model.

But I'm getting this error: "CategoryModel is not associated to ProjectModel!"

ProjectCategory.associate = () => {}, doesn't work, because associate doesn't exist.

class ProjectCategoryModel extends Model {
  projectId!: number;
  categoryId!: number;
}

ProjectCategoryModel.init({
  projectId: {
    type: INTEGER,
    primaryKey: true,
  },
  categoryId: {
    type: INTEGER,
    primaryKey: true,
  },
}, {
  sequelize: db,
  tableName: 'project_category',
  underscored: true,
  timestamps: false,
});

CategoryModel.belongsToMany(ProjectModel, {
  as: 'project',
  through: ProjectCategoryModel,
  foreignKey: 'project_id',
  otherKey: 'category_id',
});

ProjectModel.belongsToMany(CategoryModel, {
  as: 'category',
  through: ProjectCategoryModel,
  foreignKey: 'category_id',
  otherKey: 'project_id',
});

export default ProjectCategoryModel;
0 Answers
Related