【发布时间】: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 与用户表连接起来,以便在响应中也返回其数据。
【问题讨论】: