TypeORM:如何将连接列作为值放入实体中?

问题描述 投票:0回答:1

我尝试将不同表

tbl_book_locations
tbl_book_sizes
的数据连接到一个实体
book
(其他表仅供稍后讨论)。我无法更改数据库结构(遗憾的是)。

这是我在数据库中的结构:

book.entity.ts
@Entity({
  name: 'tbl_books',
  schema: 'X',
})
export class Book extends BaseItems {
  @PrimaryColumn({ name: 'item_id' })
  id: string;

  @Column({ name: 'title' })
  name: string;

  @OneToOne(() => BookLocation, (x) => x.locations, { eager: true })
  @JoinColumn({
    name: 'book_id',
    //referencedColumnName: 'geo_lat',
  })
  locations: object | null;

  geo_lat:number
  geo_lon:number

  @AfterLoad()
  setComputed() {
    //inherit from the entity
    this.geo_lat= this.locations['geo_lat'];
    this.geo_lon= this.locations['geo_lon'];
  }
booklocation.entity.ts
@Entity({
  name: 'tbl_book_locations',
  schema: 'X',
})
export class BookLocation extends BaseItems {
  @PrimaryColumn({ name: 'book_id' })
  id: string;

  @Column({ name: 'geo_lat' })
  geo_lat: number;

  @Column({ name: 'geo_lon' })
  geo_lon: number;

  //reverse but not really "needed"
  @OneToOne(() => Book)
  locations: object | null;

所以我的问题是计算和像

locations
这样的所有领域都不太方便..我的目标是最后一个像这样的对象:

{
  id: 123456,
  name: "My Book"
  geo_lat: 434.3223
  geo_lon: 23.3233
}

我目前得到的是这样的:

{
  id: 123456,
  name: "My Book",
  geo_lat: 434.3223,
  geo_lon: 23.3233,
  locations: {
      id: 123456,
      geo_lat: 434.3223,
      geo_lon: 23.3233,      
      }     
}

是否有可能实现将关系的连接列直接返回到实体中?

nestjs typeorm one-to-one relation
1个回答
0
投票

如果您不需要实体中的连接字段,则可以在查找选项中专门使用“关系”选项。

样品(未测试):

bookRepository.findOne(1, {
  relations: {
    locations: false,
  },
});

在此之后,如果需要,您可以将 null 转换为 undefined。

typeorm 查找选项文档

© www.soinside.com 2019 - 2024. All rights reserved.