Ernest Zamelczyk
Ernest Zamelczyk

Reputation: 2819

Select foreign key in TypeORM

I have table user which is in a relation ManyToMany with table activity and I wanted to select list of all activities of one user. How do I do that?

Upvotes: 1

Views: 4653

Answers (1)

Stephanie
Stephanie

Reputation: 143

i'd have this in my user entity:

  @ManyToMany(type => Activity, activity => activity.users)
  @JoinTable()
  public activities: Activity[];

and this in my activity entity:

  @ManyToMany(type => User, user => user.activities)
  public users: User[];

to select:

this.createQueryBuilder('user')
.leftJoinAndSelect('user.activities', 'activities')
.where('user.id = :id', { id })
.getMany();

assuming you have a variable id = the users id.

Upvotes: 3

Related Questions