问题描述
我刚刚开始使用 TypeORM,我正在努力让以下关系发挥作用:
I have just started using TypeORM and I'm struggling getting the following relationship to work:
User->Friends,而朋友也是用户对象.我的吸气剂,getFriends &然而,getFriendsInverse 正在工作;我现在想区分这两者.换句话说;当我执行 mysql join 时,我不想在朋友上做一个左连接,在 inverseFriends 上做另一个.
User->Friends, whereas a Friend is also a User Object.My getters, getFriends & getFriendsInverse are working, however; I do now want to distinguish between the two. In other words; when I perform a mysql join I do not want to do a left join on friends and another one on inverseFriends.
getter getFriends() 需要返回所有朋友,无论我在对象的哪一边".
The getter getFriends() needs to return all friends, regardless of which "side" the object I'm on.
有意义吗?
这是我的模型定义:
getFriends() {
// This method should also return inverseFriends;
// I do not want to return the concat version; this should
// happen on the database/orm level
// So I dont want: this.friends.concat(this.inverseFriends)
return this.friends;
}
@ManyToMany(type => User, user => user.friendsInverse, {
cascadeInsert: false,
cascadeUpdate: false,
})
@JoinTable()
friends = [];
@ManyToMany(type => User, user => user.friends, {
cascadeInsert: true,
cascadeUpdate: true,
cascadeRemove: false,
})
friendsInverse = [];
我希望有人理解我的问题 :D谢谢马特
I hope someone understands my question :DThanksMatt
推荐答案
您可以自行参考您的关系.这是一个简单的有向图示例(也就是一个节点可以有一个父节点和多个子节点).
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
).
这篇关于自引用多对多关系类型ORM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!