Search code examples
mysqltypeorm

Typeorm how to get relations of relations


I am getting the Object ChatRoomEntity with entitymanager.findOne method. The ChatRoomEntity has the variable messages which is a OneToMany - ManyToOne Relation. I have no problems to select that but how do I get the user which sent the message. Its a variable on MessageEntity with a OneToMany Relation.

So basically I want to select a room and all messages of it. But all messages should also have their values on fromUser. I select the room like this:

this.entityManager.findOne(ChatRoomEntity, {where: {id: roomToJoin.id}, relations: ['activeUsers', 'messages']}).then(roomEntity => {
// some code
}

Here my entities:

UserEntity


@Entity()
export class UserEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @CreateDateColumn()
  registrationDate: Date;

  @ManyToMany(type => ChatRoomEntity, room => room.activeUsers, {cascade: true})
  @JoinTable()
  activeChatRooms: ChatRoomEntity[];

  @OneToMany(type => ChatRoomMessageEntity, msg => msg.fromUser)
  chatRoomMessages: ChatRoomMessageEntity[];
}

ChatRoomEntity

@Entity()
export class ChatRoomEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column('varchar', {nullable: true})
  title: string;

  @OneToMany(type => ChatRoomMessageEntity, chatrmsg => chatrmsg.chatRoom)
  messages: ChatRoomMessageEntity[];

  @ManyToMany(type => UserEntity, user => user.activeChatRooms)
  activeUsers: UserEntity[];

}

ChatRoomMessageEntity

@Entity()
export class ChatRoomMessageEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column('varchar', {nullable: true})
  message: string;

  @CreateDateColumn()
  creationDate: Date;

  @ManyToOne(type => UserEntity, user => user.chatRoomMessages)
  fromUser: UserEntity;

  @ManyToOne(type => ChatRoomEntity, chatRoom => chatRoom.messages)
  chatRoom: ChatRoomEntity;

}

Solution

  • We can load sub-relations by using 'relation.subrelation' within the relations array itself like this:

    relations: ['relation1', 'relation2', 'relation2.subrelation1']

    So for your case, instead of using join you can simply do something like this:

    this.entityManager.findOne(ChatRoomEntity, {
            where: {id: roomToJoin.id},
            relations: ['activeUsers', 'messages', 'messages.fromUser'],
          }).then(roomEntity => {
    ...
    

    This is specified here: https://github.com/typeorm/typeorm/blob/master/docs/find-options.md#basic-options