You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeORM继承实体问题:如何将Meal费用正确保存为子实体

解决TypeORM表继承中子实体保存为父实体的问题

你的问题核心是TypeORM没有正确识别Meal子实体的类型,导致expense_type字段被设置为默认的DEFAULT。以下是具体的修复步骤:

1. 给子实体显式指定类型标识

默认情况下,TypeORM会给未指定类型的子实体分配DEFAULT作为expense_type值。你需要在@ChildEntity()装饰器中传入和DTO中一致的类型字符串:

@ChildEntity('MEAL') // 对应你输入参数中的"expenseType": "MEAL"
export class Meal extends Expense {
    @Column({ default: true })
    lunch: boolean;
}

这样当你保存Meal实例时,TypeORM会自动将expense_type字段设置为MEAL。

2. 确认保存逻辑的正确性

你的create方法中已经正确创建了Meal实例,但要确保使用的expenseRepository是父实体Expense的仓库(TypeORM的父实体仓库支持处理所有子实体)。如果依然有问题,可以尝试用EntityManager直接保存,确保类型被正确识别:

async create(expense: ExpenseDto) { 
    let newExpense = new Meal();
    newExpense.lunch = (expense as Meal).lunch;

    // 可选:用EntityManager替代Repository保存
    // await this.entityManager.save(newExpense);
    await this.expenseRepository.save(newExpense);
    
    return this.expenseRepository.findOneBy({ id: newExpense.id });
}

3. 枚举类型的一致性检查(如果使用了枚举)

如果你定义了ExpenseType枚举,要保证枚举值和@ChildEntity传入的字符串完全匹配,例如:

export enum ExpenseType {
    MEAL = 'MEAL',
    // 其他类型...
}

// 子实体中使用枚举值
@ChildEntity(ExpenseType.MEAL)
export class Meal extends Expense {
    // ...
}

完成以上修改后,保存Meal类型的费用时,expense_type字段就会正确设置为MEAL,而不是DEFAULT。

内容的提问来源于stack exchange,提问作者tfig-dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 13:20:17