简体   繁体   中英

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.

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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM