gpt4 book ai didi

typescript - 如何告诉 typescript getAssociation 函数存在于 Sequelize 模型中?

转载 作者:行者123 更新时间:2023-12-03 22:17:03 26 4
gpt4 key购买 nike

我有以下代码:

interface TableBAttributes {
TableBId: number;
}

interface TableAAttributes {
TableAId: number;
TableB: TableB;
}

class TableA extends Model<TableAAttributes> {}
TableA.init({
TableAId: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true
},
TableB: {
DataTypes.INTEGER,
references: {
model: TableB,
key: 'tableB_id'
},
field: 'tableB_id'
}
}, {
sequelize,
modelName: 'TableA',
tableName: 'TableA'
});

TableA.belongsTo(TableB, {
foreignKey: 'tableB_id',
as: 'TableB'
});

class TableB extends Model<TableBAttributes> {};
TableB.init({
TableBId: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true
}
}, {
sequelize,
modelName: 'TableB',
tableName: 'TableB'
});

(async () => {
const test = await TableA.findByPk(1);
const relatedTableB = await test.getTableB();
console.log(relatedTableB);
})();
如果我运行此代码,一切正常,并且我会从查询中获取关联的 TableB。我唯一的问题是,那个 typescript 提示 test.getTableB() 函数不存在,因为这个方法是由 Sequelize 创建的。
我怎么能告诉 typescript 这个方法存在?

最佳答案

检查它是否适合您。
了解更多 info

import {
Model,
HasOneGetAssociationMixin,
} from "sequelize";

interface TableBAttributes {
TableBId: number;
}

interface TableAAttributes {
TableAId: number;
}

class TableA extends Model<TableAAttributes> {
public getTableB!: HasOneGetAssociationMixin<TableB>
}

class TableB extends Model<TableBAttributes> { }

TableA.belongsTo(TableB, {
foreignKey: 'tableB_id',
as: 'TableB'
});

(async () => {
const test = await TableA.findByPk(1);
const relatedTableB = await test.getTableB();
console.log(relatedTableB);
})();

关于typescript - 如何告诉 typescript getAssociation 函数存在于 Sequelize 模型中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64390669/

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