按关系的深层属性查询

Query by deep properties on relations

我正在尝试查询 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 的深层关系?

您应该将关系视为 SQL 联接,在使用 QueryBuilder 构建查询时,使用 TypeOrm 在实体上定义它们非常简单。只要您在实体定义中启用了 link,您就可以定义连接,或者您可以使用子选择查询来处理更复杂的情况。

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();