I don't think my problem is the most difficult, but I haven't really been able to make any progress with it for some time.
I use sequelize with typescript in my backend, and I want to create associations between tables / models (many-to-many / m:n). After creating these associations, it seems that I cannot access the "magic methods" (i.e. the methods generated by sequelize to make the association easier to use).
// association between tasks and employees was defined
const task = await DB.Tasks.findByPk(1)
// task.addEmployee() or such methods doesnt exist!
Using sequelize v6.37.2
Before we get to my code, I would like to give you a little important information first.
console.log(mymodel.associations) // works, no error
will return my definied asscoation. I have also searched on github for a repository that might use a similar structure to my models (official sequelize docs template) but to no avail. I tried to stick to the official sequelize docs:
https://sequelize.org/docs/v6/other-topics/typescript/
Here is one of my models (the other one has the same structure):
// Task is a simple interface containing all attributes
export type TaskCreationAttributes = Optional<Task, "id">
export class TaskModel extends Model<Task, TaskCreationAttributes> {
declare id: number
declare name: string
declare description: string
}
export default function (sequelize: Sequelize): typeof TaskModel {
TaskModel.init(
{
id: {
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
name: {
allowNull: false,
type: DataTypes.STRING(255),
},
description: {
allowNull: true,
type: DataTypes.TEXT,
}
},
{
tableName: "tasks",
sequelize,
},
)
TaskModel.belongsToMany(EmployeeModel, { through: "task_positions"})
EmployeeModel.belongsToMany(TaskModel, { through: "task_positions"})
return TaskModel
}
You need to declare such "magic" methods explicitly using provided mixin interfaces from Sequelize (see the link you mentioned):
declare getEmployees: BelongsToManyGetAssociationsMixin<Emplyee>;