NestJS, typeORM relation에서 다른 컬럼 이름을 사용하기

2022. 10. 31. 17:52개발/Node

NestJS에서 typeORM을 사용해 relation을 구현하게 되었습니다.
relation에 사용한 컬럼 이름은 일종의 커스텀인데 그 과정을 나누고자 합니다.

Entity

저는 2개의 모델을 사용했습니다.

Product 테이블에는 id, name이 있고 Month 테이블에는 id, product_id, month가 있습니다.
Month 테이블에 있는 product_id가 일종의 FK입니다. (실제로 fk를 맺지는 않았습니다.)

export class Product {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;
}
export class Month {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  product_id: number;

  @Column()
  month: number;
}

 

Relations

https://docs.nestjs.com/techniques/database#relations

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reac

docs.nestjs.com

위 내용은 조금 부족하게 나와 있는데 OneToMany를 사용하기 위해서는 ManyToOne도 같이 사용해줘야 한다고 나와있습니다.

If you want to use @OneToMany, @ManyToOne is required. However, the inverse is not required: If you only care about the @ManyToOne relationship, you can define it without having @OneToMany on the related entity.

https://typeorm.io/many-to-one-one-to-many-relations#

코드를 아래처럼 수정했습니다.

export class Product {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @OneToMany(() => Month, (month) => month.product)
  months: Month[];
}
export class Month {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  product_id: number;

  @Column()
  month: number;

  @ManyToOne(() => Product, (product) => product.months)
  product: Product;
}

 

Unknown column

위처럼 작성하고 실행을 하면 Unknown column 에러가 나타납니다.

별다른 설정이 없으면 productId와 같은 컬럼을 자동으로 찾아주는 것으로 보입니다.
실제로 예제를 보아도 userId와 같이 사용하는 곳들을 볼 수 있었습니다.

저는 새롭게 작성한 컬럼 이름(product_id)을 사용해야 했기에 추가적인 설정이 필요했습니다.

 

@JoinColumn

JoinColumn에 대한 내용을 보면 아래와 같이 설명이 되어 있습니다.

@JoinColumn not only defines which side of the relation contains the join column with a foreign key, but also allows you to customize join column name and referenced column name.

https://typeorm.io/relations#joincolumn-options

위 내용을 참고해서 Month에 @JoinColumn을 추가합니다.

export class Month {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  product_id: number;

  @Column()
  month: number;

  @ManyToOne(() => Product, (product) => product.months)
  @JoinColumn({ name: 'product_id' })
  product: Product;
}

 

여기까지 진행하면 내가 원하는 컬럼 이름으로 relation을 사용할 수 있습니다.