TypeORM. Find Where with Many-To-Many Relation

23 Views Asked by At

I have two entities: Chat and User with bi-directional many-to-many relation between. My goal is to find chats that are relevant to the user with a specific id. The issue is that when I use find/where it returns a record with only one user inside chat.members (the one that has firebaseId = user.uid) but not the other user who's also present in the chat.

// Chat.ts
@Entity()
export class Chat implements IChat {
  @PrimaryColumn("text")
  id: string

  @ManyToMany(() => User, (user) => user.chats)
  @JoinTable()
  members: User[]

  @OneToMany(() => Message, (message) => message.chat)
  messages: Message[]
}
// User.ts
@Entity()
export class User implements IUser {
  @PrimaryGeneratedColumn()
  id: number

  @Column("text")
  firebaseId: string

  @Column("text")
  displayName: string

  @Column("text")
  email: string

  @Column("text")
  photoURL: string

  @Column("boolean")
  online: boolean

  @OneToMany(() => Message, (message) => message.author)
  messages: Message[]

  @ManyToMany(() => Chat, (chat) => chat.members)
  chats: Chat[]
}

// Query.ts
async findUserChats(_, __, { user }) {
  if (!user) return []

  return chatRepository.find({
    relations: ["members", "messages"],
    where: {
      members: {
        firebaseId: user.uid,
      },
    },
  })
}

0

There are 0 best solutions below