본문 바로가기

NestJS

[NestJS] TypeORM 관계(Relation) 정리

NestJS에서 TypeORM을 사용할 때 가장 많이 사용하는 관계 매핑을 예제 코드 중심으로 정리한 포스트이다. 

(개인 복습용으로 작성)


1: 1 관계 설정 (UserEntity & ProfileEntity)

  • 한 명의 사용자(User)는 하나의 프로필(Profile)만 가질 수 있음.
  • '@OneToOne' + '@JoinColumn' 사용.
  • 반드시 'JoinColumn'은 관계의 소유 측(owner side)에만 작성.
// user.entity.ts
@OneToOne(() => ProfileModel, (profile) => profile.user, { ...옵션 })
profile: ProfileModel;

// profile.entity.ts
@OneToOne(() => UserModel, (user) => user.profile)
@JoinColumn()
user: UserModel;

 

 

1 : N 관계 설정 (UserEntity & PostEntity)

  • 한 명의 사용자(User)는 여러 갱의 게실을 가질 수 있음 (OneToMany)
  • 게시글(Post)는 작성자(User)를 하나만 가짐 (ManyToOne)
// user.entity.ts
@OneToMany(() => PostModel, (post) => post.author)
posts: PostModel[];

// post.entity.ts
@ManyToOne(() => UserModel, (user) => user.posts)
@JoinTable() // ❌ 일반적으로 ManyToOne에서는 필요 없음
author: UserModel;

 

 

N : M 관계 설정 (PostEntity & TagEntity)

  • 하나의 게시글(Post)은 여러 개의 태그(Tag)를 가질 수 있음
  • 하나의 태그(Tag)는 여러 개의 게시글(Post)에 달릴 수 있음
// post.entity.ts
@ManyToMany(() => TagModel, (tag) => tag.posts)
@JoinTable()
tags: TagModel[];

// tag.entity.ts
@ManyToMany(() => PostModel, (post) => post.tags)
posts: PostModel[];

 

 

기타 유용한 데코레이터 정리

@PrimaryGeneratedColumn() 기본 키 + 자동 증가
@CreateDateColumn() 생성일 자동 기록
@UpdateDateColumn() 수정일 자동 기록
@VersionColumn() 엔티티 변경 시 버전 증가
@Generated('increment') 별도의 자동 증가 컬럼
@Column({ type: 'enum', enum: EnumType }) enum 타입 지정

 

+ @Column() 옵션 정리

@Column({
    name: 'title',        // DB에 저장될 실제 컬럼명
    length: 300,          // 문자열 최대 길이
    nullable: true,       // null 허용 여부
    update: true,         // 수정 가능 여부
    select: false,        // 쿼리 시 기본 조회 대상에서 제외
    default: 'default value', // 기본 값
    unique: true          // 유일한 값인지 여부
})
title: string;

 

name DB에서 실제 사용하는 컬럼명. 생략 시 프로퍼티 이름(title)이 그대로 사용됨
length varchar 타입의 최대 길이 설정 (예: 300자)
nullable true일 경우, 해당 컬럼은 NULL 값 허용
update false일 경우, 최초 저장 이후 값을 수정할 수 없음
select false로 설정하면, find() 시 기본적으로 해당 컬럼은 쿼리에 포함되지 않음
default 값이 없을 때 자동으로 채워질 기본값
unique 해당 컬럼 값이 중복되면 안 되는 경우 사용 (DB 인덱스 생성됨)