TypeORM无法从ManyToOne关联中获取值的问题求助
问题:TypeORM关联实体无法获取值,返回undefined
实体定义代码
@Entity() export class InvestorCategory extends BaseEntity { @PrimaryGeneratedColumn('uuid') public id: string; @Column({ unique: true }) public value: string; @Exclude() @OneToMany(() => Contract, (entity) => entity.investor_category) public contracts: Contract[]; } @Entity() export class Contract extends BaseEntity { @PrimaryGeneratedColumn('uuid') public id: string; @ManyToOne(() => InvestorCategory, (entity) => entity.contracts) public investor_category: InvestorCategory; @Column({ nullable: true }) public comment: string; }
问题详情
数据库中contract表的外键列investorCategoryId已正确填充,但通过以下代码获取Contract实例后:
const contract = await this.contractRepository.findOne({where: { id } });
访问contract?.investor_category或contract?.investor_category?.id时返回undefined,尽管TypeScript提示这些属性存在。
解决方案
- TypeORM的
findOne方法默认不会自动加载关联实体,必须显式指定要加载的关联。修改查询代码,添加relations选项即可:const contract = await this.contractRepository.findOne({ where: { id }, relations: ["investor_category"] // 显式加载关联的investor_category }); - 若需要更复杂的查询逻辑,也可以使用
QueryBuilder实现关联查询:const contract = await this.contractRepository .createQueryBuilder("contract") .leftJoinAndSelect("contract.investor_category", "investor_category") .where("contract.id = :id", { id }) .getOne(); - 你的实体关联定义是正确的,
@ManyToOne与@OneToMany的映射关系没有问题,无需修改实体代码。
内容的提问来源于stack exchange,提问作者yarex
相关产品推荐
相关产品推荐

