【问题标题】:Join column (id) with a table in NestJS using TypeORM使用 TypeORM 将列(id)与 NestJS 中的表连接起来
【发布时间】:2021-06-01 12:51:46
【问题描述】:

我正在用 NodeJS 和 TypeORM 做一个服务器端应用程序。

我有这些表:

users
--------------------------------------------
 id        |  firstName            | lastName
--------------------------------------------
1          |  Lorem                | Ipsum

companies
------------------------------------------------------------
id        |  name
------------------------------------------------------------
1         |  Lorem

transfers
------------------------------------------------------------
id        |  points            | userId       | companyId
------------------------------------------------------------
1         |  10                | 1            | 1

公司实体

@Entity({ name: 'companies' })
export class CompanyEntity extends BaseEntity {
  @Column()
  name: string;

  @OneToMany(() => TransferEntity, (transfer) => transfer.company)
  transfers: TransferEntity[];
}

转移实体

@Entity({ name: 'transfers' })
export class TransferEntity extends BaseEntity {
  @Exclude()
  @ManyToOne(() => CompanyEntity, (company) => company.transfers)
  company: CompanyEntity;

  @Column()
  points: number;

  @Column()
  userId: number;
}

定义传输和用户之间的关系不是我的选择。

我想通过其 ID 获取公司的所有转移,并将userID 列与真实用户及其数据加入users 表中。

async findAllTransfersByCompanyId(id: number): Promise<TransferEntity[]> {
    // 1. Find the company by its ID
    const company = await this.companyRepository.findOne(id, {
      // 2. Get all the transfers
      relations: ['transfers'],
      // 3. Join the userId of a transfer with the user data in the 'users' table
      join: {
        alias: 'users',
        innerJoin: {
          userId: 'users.id',
        },
      },
    });

    return company.transfers;
  }

未找到与实体中的属性路径 ID 的关系。

我不太了解join的逻辑,也许有最简单的方法。

我的目标是将转移表的userID 与用户表连接起来,以便在响应中也返回其数据。

【问题讨论】:

    标签: nestjs typeorm


    【解决方案1】:

    你需要定义transfersusers之间的关系,就像你在transferscompany之间定义的一样

    @Entity({ name: 'transfers' })
    export class TransferEntity extends BaseEntity {
      @Exclude()
      @ManyToOne(() => CompanyEntity, (company) => company.transfers)
      company: CompanyEntity;
    
      @Column()
      points: number;
    
      @ManyToOne((type) => User)
      user: User;
    }
    

    【讨论】:

    • 定义这种关系不是我的选择,这就是我没有的原因。我想以另一种方式建立关系。
    猜你喜欢
    • 2020-07-22
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 2021-12-03
    • 2019-08-13
    • 2022-01-21
    相关资源
    最近更新 更多