Sequelize typescript 无关联方法

问题描述 投票:0回答:1

我不认为我的问题是最困难的,但我已经有一段时间没有真正取得任何进展了。

我的问题是什么?

我在后端使用带有打字稿的sequelize,并且我想创建表之间的关联/模型(多对多/ m:n)。创建这些关联后,我似乎无法访问“神奇方法”(即由sequelize生成的使关联更易于使用的方法)。

// association between tasks and employees was defined

const task = await DB.Tasks.findByPk(1) 
// task.addEmployee() or such methods doesnt exist! 

使用 sequelize v6.37.2

我尝试了什么?

在我们讨论我的代码之前,我想先向您提供一些重要信息。

console.log(mymodel.associations) // works, no error  

将返回我的定义的关联。我还在 github 上搜索了一个可能使用与我的模型类似结构的存储库(官方续集文档模板),但无济于事。我尝试遵循官方的续集文档:

https://sequelize.org/docs/v6/other-topics/typescript/

我的代码

这是我的一个模型(另一个具有相同的结构):

// 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
}
typescript sequelize.js associations
1个回答
0
投票

您需要使用 Sequelize 提供的 mixin 接口显式声明此类“神奇”方法(请参阅您提到的链接):

declare getEmployees: BelongsToManyGetAssociationsMixin<Emplyee>;
© www.soinside.com 2019 - 2024. All rights reserved.