TypeOrm Many to Many of the same entity

Viewed 1525

I'm trying to figure out how to create a User Entity with a relation on the friends column that contains other User entities. Joined through a join table of userId pairs. This sort of works:

@Entity('user')
export class User {
  @PrimaryGeneratedColumn('uuid')
  id: string;
  @ManyToMany(
    () => User,
    (user) => user.friends
  )
  @JoinTable()
  friends: User[];
}

It does create a relation and I can populate the join table with ids and retrieve the data but it seems to be only one way.

Here is the join table:

 userId_1 | userId_2 
------------+------------

What I mean by one way is that it the linkage appears to be from userId_1 -> userId_2 and not both ways. Is there any way to improve on this? I'd like to be able to get the relation from either side based on the one row entry

1 Answers

You need to add the other side of the relation. I'm using "followers" instead of "friends" since that reflects clearly the direction each relation has.

This way you can do something like user.followers and user.following

@ManyToMany(() => User, (user) => user.following)
@JoinTable()
followers: User[];
    
@ManyToMany(() => User, (user) => user.followers)
following: User[];
Related