gpt4 book ai didi

typescript - 是否有与 TypeScript 兼容的方式来使用 Sequelize 访问关联实体?

转载 作者:搜寻专家 更新时间:2023-10-30 21:49:00 25 4
gpt4 key购买 nike

我正在开发一个运行 Sequelize 的 TypeScript 应用程序。这是一个最小的示例模型:

import * as Sequelize from 'sequelize';

export interface MyAttribute {
id: number,
descr: string
}

export interface MyInstance extends Sequelize.Instance<MyAttribute>, MyAttribute { }

export interface MyModel extends Sequelize.Model<MyInstance, MyAttribute> { }

export default class MyManager {

//[...]

constructor() {

this.model = this.sequelize.define<MyInstance, MyAttribute>("MyEntity", {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
descr: {
type: Sequelize.INTEGER
}
});
}

public initRelations() {
this.model.belongsTo(OtherModel.model);
this.model.sync({force:true});
}
}

现在我想通过 MyInstance 对象访问 OtherModel 的关联实体。我尝试了 getOtherModels() 但这在 TypeScript 编译期间无效。在这个 TypeScript 环境中是否有任何其他方法可以访问关联的实体及其属性?

感谢您的帮助。

最佳答案

Sequelize 会在运行时将 getOtherModels 等方法添加到对象中,因此您只需告诉 Typescript 它们将在运行时存在于 MyModel 实例上,这样您就可以使用它们:

export interface MyInstance extends Sequelize.Instance<MyAttribute>, MyAttribute { 
getOtherModels(): Promise<OtherModel[]>
}

关于typescript - 是否有与 TypeScript 兼容的方式来使用 Sequelize 访问关联实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49350044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com