【问题标题】:Postgres / TypeORM - multiple joins. How should I format the query?Postgres / TypeORM - 多个连接。我应该如何格式化查询?
【发布时间】:2020-02-21 16:13:34
【问题描述】:

我正在构建一个后端微服务,它使用 postgres 作为 DB 和 TypeORM (NodeJs) 库来管理与它的连接。

假设我的数据库包含 3 个表/实体。

  1. 用户表(主列是-id)
  2. Profile 表(主列 id,然后外键 user_id 指向用户表 id 列) 可能有多个个人资料行与一位用户相关联
  3. 经验表(主列id,然后外键profile_id列指向profile表id列) 可能有多个体验行与一份个人资料相关联

a) 我可以执行一个复杂的查询来获取配置文件行和与之关联的所有经验行吗?

  getFullProfile(profileId: number) {
    return this.profileEntityRepository.createQueryBuilder('profile')
      .where('profile.id = :profileId', { profileId })
      .innerJoinAndMapMany('profile.experience', ExperienceEntity, 'experience', 'experience.id = profile.id')
      .getOne();
  }

遗憾的是,这不会返回任何结果(如果我注释掉 innerJoinAndMapMany 行,它会返回)。

有什么建议吗?它不必是基于 TypeORM api 的答案,简单的普通查询就足够了。

谢谢!

【问题讨论】:

    标签: postgresql typeorm


    【解决方案1】:

    好的,我解决了。

    我将 typeORM 查询更改为:

      getFullProfile(profileId: number) {
        return this.profileEntityRepository.createQueryBuilder('profile')
          .leftJoinAndSelect('profile.experiences', 'experience')
          .where('profile.id = :profileId', { profileId })
          .getOne();
      }
    

    为了让这个工作,我还需要在配置文件实体中添加 OneToMany 列,如下所示:

      @OneToMany(type => ExperienceEntity, experience => experience.profile)
      experiences: ExperienceEntity[];
    

    这不会在表中创建“经验”列,而是 TypeORM 需要了解情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      • 2016-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-30
      相关资源
      最近更新 更多