简体   繁体   English

如何在 Nest.js 中查询多个@ManyToMany 中的数据

[英]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 .众所周知,使用relations来查询具有ManyToMany关系的数据。 But how to query in mutiple ManyToMany ?但是如何在多个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 .现在我想使用classificationRepository来查询与Article相关的数据,并且Article应该与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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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