Although I don't consider my problem to be the most challenging, I've been struggling to make any headway with it for quite some time.
What is the issue I'm facing?
In my backend, I am using sequelize alongside typescript and I am attempting to establish associations between tables/models (specifically many-to-many relationships). However, after setting up these associations, I am unable to utilize the "magic methods" provided by sequelize to facilitate these associations.
// defined association between tasks and employees
const task = await DB.Tasks.findByPk(1)
// task.addEmployee() or similar methods are missing!
Using sequelize v6.37.2
What steps have I taken so far?
Before delving into my code, I feel it is important to share some key details first.
console.log(mymodel.associations) // successfully executed without errors
This will display my defined association. I have also scoured GitHub for repositories utilizing a similar model structure to mine (following the official sequelize docs template) but have found no solutions. I have made efforts to adhere to the guidelines provided in the official sequelize documentation:
https://sequelize.org/docs/v6/other-topics/typescript/
My Implementation
Below is one of my models (the other model follows the same structure):
// Task interface defining 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
}