I have just started using TypeORM and I\'m struggling getting the following relationship to work:
User->Friends, whereas a Friend is also a User Object. My getters, getF
You can self-reference your relations. Here is an example of a simple directed graph (aka a node can have a parent and multiple children).
@Entity()
export class Service extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
@Index({ unique: true })
title: string;
@ManyToOne(type => Service, service => service.children)
parent: Service;
@OneToMany(type => Service, service => service.parent)
children: Service[];
}
An important note to keep in mind is that these relations are not auto loaded when reading an object from the DB with find*
functions.
To actually load them, you have to use query builder at the moment and join them. (You can join multiple levels.) An example:
let allServices = await this.repository.createQueryBuilder('category')
.andWhere('category.price IS NULL')
.innerJoinAndSelect('category.children', 'product')
.leftJoinAndSelect('product.children', 'addon')
.getMany();
Please note how I used different names to reference them (category
, product
, and addon
).
I hope someone understands my question
Yeah, here is the problem. I don't know what are trying to do. Friend
is a separate class or it's still User->User[]
relation?
Maybe this will help you: https://typeorm.github.io/tables-and-columns.html#closure-table