【问题标题】:How to query data in mutiple @ManyToMany in Nest.js如何在Nestjs中查询多个@ManyToMany中的数据
【发布时间】:2019-07-31 22:48:15
【问题描述】:

众所周知,使用relations 来查询具有ManyToMany 关系的数据。但是如何查询多个ManyToMany?可能你很困惑,请让我给你解释一下。

@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[];
}

现在我想用classificationRepository查询数据关联Article,而Article应该关联User

但我不知道该怎么做。

【问题讨论】:

    标签: javascript node.js typescript nestjs typeorm


    【解决方案1】:

    您可以将多个联接添加在一起。首先,加入文章,然后在您的第二次加入中为用户引用文章:

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

    【讨论】:

      【解决方案2】:

      如果文章与类别具有双向多对多关系,并且您想要获取某个类别的文章。您可以加载该类别的文章,然后返回它们

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

      【讨论】:

        猜你喜欢
        • 2020-06-29
        • 2021-09-23
        • 1970-01-01
        • 2021-07-03
        • 1970-01-01
        • 2021-09-10
        • 2021-04-07
        • 2019-01-15
        • 2022-07-02
        相关资源
        最近更新 更多