This is the entities I defined:
@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;
}
When it comes to the database, the foreign key is present in the database in the contract table, column investorCategoryId and when I create and save a new contact this column is populated with the proper id.
But when I try doing something along these lines (and TypeScript hints these values):
contract?.investor_category
contract?.investor_category?.id
I get an undefined value.
Is there a step I am missing? Or something wrong with the code? Should I use something like QueryBuilder instead?
EDIT: I forgot to mention - this is the way I get the contract from the database:
const contract = await this.contractRepository.findOne({where: { id } });
According to the docs - I should have specified a relations field in the FindOptions.
Example:
const userRepository = dataSource.getRepository(User)
const users = await userRepository.find({
relations: {
photos: true,
},
})
This probably acts as a join in the SQL query.
I didn't test this yet, but this is most likely the answer to my question.