Search code examples
postgresqltypescripttypeorm

Query by deep properties on relations


I am trying to query the memberRepository on two deep relations

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 })

This isn't working, how can I query a deep relation with typeorm?


Solution

  • You should think of relations as SQL joins, it is quite simple with TypeOrm to define them on entities as you build query with QueryBuilder. As long as you have a link enabled in your entity definition you can define a join, or you can use a subselect query otherwise for more complex cases.

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