TypeORM: How to get joined columns into entity as value?

46 Views Asked by At

I try to join data of different tables tbl_book_locations, tbl_book_sizes into one entity book (the other tables are just for later discussions). I cannot change the database structure (sadly).

So this is my structure in the database:

book example

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;

So my problem is that the computing and all the fields like locations are not really handy.. I aim for a object like this at the end:

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

What I get currently is like:

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

Is it even possible to achieve to get the joined columns of the relation back directly into the entity?

1

There are 1 best solutions below

4
TaekYoung On

If you don't need joined field at entity, you can use "relations" option exclusively at find option.

sample (not tested):

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

And after this you can convert null to undefined if needed.

typeorm find options doc