更新时间:2023-02-15 19:31:45
您可以自行参考您的关系.这是一个简单的有向图示例(也就是一个节点可以有一个父节点和多个子节点).
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[];
}
要记住的一个重要注意事项是,当使用 find*
函数从数据库读取对象时,这些关系不会自动加载.
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();
请注意我如何使用不同的名称来引用它们(category
、product
和 addon
).
Please note how I used different names to reference them (category
, product
, and addon
).