这是我定义的实体:
@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 列中,当我创建并保存新的 contact 时,此列将填充正确的 id。
但是当我尝试按照这些思路做一些事情时(并且 TypeScript 提示了这些值):
contract?.investor_category
contract?.investor_category?.id
我得到一个未定义值。
我是否缺少一个步骤?或者代码有什么问题?我应该使用类似 QueryBuilder 的东西吗?
编辑: 我忘了提及 - 这是我从数据库获取 contract 的方式:
const contract = await this.contractRepository.findOne({where: { id } });
我做了一个解决方法 - 使用 TypeORM 的 Query Builder
const user = await this.userRepository
.createQueryBuilder('user')
.innerJoinAndSelect('user.contract', 'contract')
.innerJoinAndSelect(
'contract.investor_category',
'investor_category',
)
.where('user.id = :id', { id })
.getOne();
这并不能回答为什么第一个解决方案不起作用,但提供了一个可行的解决方案