如何解决序列化V5-> V6升级:Typescript错误属性'x'在类型'y'上不存在
我将从sequelize 5.x.x升级到6.x.x。 在sequelize v5中,一切正常,但是当我升级时,当我想使用包含中的对象时,通过关联生成的所有属性都将出现打字错误。 我也尝试了docstring中的示例,但没有成功。
我希望任何人都能帮助我!
型号: Participant.js
import { Model,DataTypes } from 'sequelize';
import { STATUS } from '@bb/shared-core/dist/constants/participant';
import sequelize from '@bb/db';
import User from '@bb/components/erp/v1/modules/users/models/User';
import OrderItem from '@bb/components/ecommerce/v2/modules/orders/models/OrderItem';
import Contact from '@bb/components/erp/v1/modules/contacts/models/Contact';
import { DeserializedModel } from '../interfaces/Participant';
export class Participant extends Model implements DeserializedModel {
id!: number;
fkUser: number;
fkOrderItem: number;
fkContact: number;
adminNotes: string;
trainerNotes: string;
attendance: string;
status: string;
readonly createdAt: Date;
readonly updatedAt: Date;
}
Participant.init({
fkUser: {
type: DataTypes.NUMBER,field: 'fk_user'
},fkOrderItem: {
type: DataTypes.NUMBER,field: 'fk_order_item'
},fkContact: {
type: DataTypes.NUMBER,field: 'fk_contact'
},trainerNotes: {
type: DataTypes.STRING,field: 'trainer_notes'
},adminNotes: {
type: DataTypes.STRING,field: 'admin_notes'
},attendance: {
type: DataTypes.ENUM('confirmed','unconfirmed'),field: 'attendance'
},status: {
type: DataTypes.ENUM(STATUS.REBOOKED,STATUS.CANCELLED,STATUS.PARTICIPATING),field: 'status',defaultValue: 'participating'
}
},{
sequelize,modelName: 'participant'
});
Participant.belongsTo(User,{
as: 'user',foreignKey: 'fk_user',targetKey: 'id'
});
Participant.belongsTo(OrderItem,{
as: 'orderItem',foreignKey: 'fk_order_item',targetKey: 'id'
});
OrderItem.hasMany(Participant,{
as: 'participants',sourceKey: 'id'
});
Participant.belongsTo(Contact,{
as: 'contact',foreignKey: 'fk_contact',targetKey: 'id'
});
if (process.env.NODE_ENV === 'test') {
Participant.sync();
}
export default Participant;
这是使用模型的函数: ParticipantService.js
private async getEventIdFromParticipant(participantId: number): Promise<number|undefined> {
const participant = await Participant.findOne({
where: {
id: participantId,},include: [
{
model: OrderItem,as: 'orderItem',}
]
});
return participant?.orderItem?.fkEvent;
}
错误在return语句的 ParticipantService.js 中。
Property 'orderItem' does not exist on type 'Participant'
解决方法
您也需要在类中定义它:
import { Model,DataTypes,BelongsTo } from 'sequelize';
export class Participant extends Model implements DeserializedModel {
id!: number;
fkUser: number;
fkOrderItem: number;
fkContact: number;
adminNotes: string;
trainerNotes: string;
attendance: string;
status: string;
public readonly orderItem?: OrderItem;
public static associations: {
orderItem: BelongsTo<Participant,OrderItem>;
};
readonly createdAt: Date;
readonly updatedAt: Date;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。