我试图查询两个深层关系的memberRepository
const memberRepository = connection.getRepository(Member);
const where = {
"contact": {
"user":{
"uuid": "3322ebc7-7327-4567-95a9-619d36b8e0a6"
}
},
"organization": {
"uuid": "014f2226-729f-4b9f-bf59-5a6e8b8da781",
}
};
const relations = ['contact', 'contact.user', 'organization']
const x = await memberRepository.findOne({ where, relations })
这不起作用,如何查询与typeorm的深层关系?
答案 0 :(得分:1)
您应该将关系视为SQL连接,在使用QueryBuilder构建查询时,使用TypeOrm在实体上定义关系非常简单。只要您在实体定义中启用了链接,就可以定义联接,或者对于更复杂的情况也可以使用子选择查询。
const result = await memberRepository.createQueryBuilder("member")
.leftJoinAndSelect("member.contact", "contact")
.leftJoinAndSelect("contact.user", "user")
.leftJoinAndSelect("member.organization", "organization")
.where("user.uuid = :userUuid", {
userUuid: "3322ebc7-7327-4567-95a9-619d36b8e0a6"
})
.andWhere("organization.uuid = :organizationUuid", {
organizationUuid: "014f2226-729f-4b9f-bf59-5a6e8b8da781"
})
.getOne();