Eve-Sama
Eve-Sama

Reputation: 2658

How to query data in mutiple @ManyToMany in Nest.js

As we all know that use relations to query data which has a relation ManyToMany. But how to query in mutiple ManyToMany? Maybe you are confused, please let me explain to you.

@Entity()
export class Article {
  @ManyToMany(type => Classification, classification => classification.articles)
  classifications: Classification[];

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

@Entity()
export class Classification {
  @ManyToMany(type => Article, article => article.classifications)
  @JoinTable()
  articles: Article[];
}

@Entity()
export class User {
  @ManyToMany(type => Article, article => article.users)
  @JoinTable()
  articles: Article[];
}

Now I wanna use classificationRepository to query data relate Article, and the Article should relate User.

But idk how to do that.

Upvotes: 3

Views: 3143

Answers (2)

Stijno24
Stijno24

Reputation: 1

If articles has a bi directional many-to-many relation to categories and you want to get the articles of a category. You can load the articles on the category and then return them


const category = await this.categoryRepository.findOne(params.id, {
  relations: ["articles"]
});

return category.articles

Upvotes: 0

Kim Kern
Kim Kern

Reputation: 60357

You can add multiple joins together. First, join the articles, then reference the articles in your second join for the users:

this.categoryRepository.createQueryBuilder('classification')
  .leftJoinAndSelect(
    'classification.articles',
    'article',)
  .leftJoinAndSelect(
    'article.users',
    'user')
  .where('article.id = :id', { id: '1' })
  .getMany();

Upvotes: 3

Related Questions