Search code examples
node.jstypescripttypeorm

TypeORM get one side of a many to many relationship


I have got two entities: User and Organisation. These entities have a Many-to-Many relationship with each other. (A user can belong to multiple organisations and an organisation has multiple users.)

I have an endpoint /organisation/:id/members this endpoint should return only the users belonging to the organisation of :id.

I have created a query as follows:

    const members = await getConnection()
      .createQueryBuilder(Organisation, 'org')
      .where('org.id = :orgId', { orgId })
      .innerJoinAndSelect('org.members', 'member')
      .select('member')
      .getMany();

This returns an empty array, except when getRawMany is used. Then it returns the following:

[
  {
    "member_id": 1,
    "member_email": "[email protected]",
    "member_firstName": "John",
    "member_middleName": "",
    "member_lastName": "Doe"
  }
]

I would like to know how I get getMany() to return User entities.

Update: I have the following example which does work. However, it requires the user to give the joinTable a name.

await getConnection()
      .createQueryBuilder(User, 'user')
      .innerJoinAndSelect(
        'organisation_members',
        'member',
        'member.userId = user.id',
      )
      .where('member.organisationId = :orgId', { orgId })
      .getMany();

Solution

  • NEW ANSWER: My entities were setup incorrectly. I specified my ManyToMany relationship like this (incorrect!):

    @ManyToMany(type => User)
    members: User[];
    

    Because this is a bi-directionaly relationship, I must specify on what field the user has the relationship towards the organisations:

    
    @ManyToMany(
      type => User,
      user => user.organisations,
    )
      members: User[];
    

    And my User entity has:

    @ManyToMany(
      type => Organisation,
      org => org.members,
    )
    organisations: Organisation[];
    

    Use the TypeORM Query Relation Builder to get all members.

    Updated once again:

    return getConnection()
          .createQueryBuilder()
          .relation(Organisation, 'members')
          .of(orgId)
          .loadMany();