【问题标题】:Create query builder that the source table (FROM) is a join table in TypeORM在 TypeORM 中创建源表 (FROM) 是连接表的查询构建器
【发布时间】:2022-01-21 12:18:10
【问题描述】:

我正在尝试使用QueryBuilder 在 TypeORM 中实现以下 SQL:

SELECT
  user_places.user_id,
  place.mpath
FROM
  public.user_root_places_place user_places
INNER JOIN
  public.place place
  ON place.id = user_places.place_id

实体是:

@Entity()
export class User {
  @Column({ unique: true, primary: true })
  id: string;

  @ManyToMany(() => Place)
  @JoinTable()
  rootPlaces: Place[];
}

@Entity()
export class Place {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  mpath: string;
}

当您创建查询构建器时,您必须使用一些实体或表,但连接表被 TypeORM“隐藏”


我知道我可以替换内部连接表顺序,它会解决问题,但我正在寻找源表何时是连接表

【问题讨论】:

    标签: sql typescript postgresql typeorm


    【解决方案1】:

    如果您不想使用生成的名称,只需明确指定连接表名称

    @Entity()
    export class User {
      @Column({ unique: true, primary: true })
      id: string;
    
      @ManyToMany(() => Place)
      @JoinTable({
        name: 'user_places' // <---
      })
      rootPlaces: Place[];
    }
    

    然后:

    createQueryBuilder('user_places')
      .select(['user_places.userId', 'place.mpath'])
      .innerJoin(Place, 'place', 'place.id = user_places.place_id')
      .getMany();
    

    【讨论】:

      猜你喜欢
      • 2020-11-30
      • 1970-01-01
      • 2015-03-02
      • 1970-01-01
      • 2015-04-12
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 2013-04-07
      相关资源
      最近更新 更多