简体   繁体   English

TypeOrm/PostgreSQL createQueryBuilder:来自连接表的 select 列

[英]TypeOrm/PostgreSQL createQueryBuilder: select column from joined table

I want to select only a column from a table that I'm joining into.我只想 select 我要加入的表中的一列。 A separator has a facility , a facility has a customer , and I want to select customer.id by providing a separatorId . separator有一个facility ,一个facility有一个customer ,我想通过提供一个separatorId来 select customer.id

Below is what I have tried, but this returns a Separator .下面是我尝试过的,但这会返回一个Separator

return await this.separatorRepository
  .createQueryBuilder('separator')
  .select(['customer.companyId'])
  .innerJoin('separator.facility', 'facility')
  .innerJoin('facility.customer', 'customer')
  .where('separator.id = :separatorId', { separatorId })
  .getOne();

How do I change this query to get customer.id ?如何更改此查询以获取customer.id

I suppose your joined tables are not selected from because you use innerJoin method instead of innerJoinAndSelect .我想您的连接表没有被选中,因为您使用的innerJoin方法而不是innerJoinAndSelect Additionally, since getOne returns objects with your entity type ( Separator in your case), you need to make sure the relations between Separator , Facility , and Customer are properly specified.此外,由于getOne返回具有您的实体类型(在您的情况下为Separator )的对象,因此您需要确保正确指定SeparatorFacilityCustomer之间的关系。

Entities:实体:

@Entity()
export class Customer {
    @PrimaryColumn()
    id: number;
}

@Entity()
export class Facility {
    @PrimaryColumn()
    id: number;

    @OneToOne(() => Customer)
    @JoinColumn()
    customer: Customer;
}

@Entity()
export class Separator {
    @PrimaryColumn()
    id: number;

    @OneToOne(() => Facility)
    @JoinColumn()
    facility: Facility;
}

Query:询问:

return await this.separatorRepository
  .createQueryBuilder('separator')
  .innerJoinAndSelect('separator.facility', 'facility')
  .innerJoinAndSelect('facility.customer', 'customer')
  .where('separator.id = :separatorId', { separatorId })
  .getOne();

The query yields you the instance of Separator with the joined entities, so you could get your customer.id from there.该查询为您生成带有连接实体的Separator实例,因此您可以从那里获取您的customer.id

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

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