코딩/TypeORM

Relationship

춘 몽 2024. 10. 15. 00:01

@Join 없는 곳 설정 안하면 단방향이 됨.

- OneToOne

// User
@OneToOne(() => ProfileModel, (profile) => profile.user)
profil: ProfileModel;

// Profile
@OneToOne(() => UserModel, (user) => user.profil)
@JoinColumn() // JoinColumn 있는곳에 컬럼 생김
user: UserModel;

JoinColumn 있는곳에 컬럼 생김

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

 

 

- OneToMany, ManyToOne

// User
@OneToMany(() => PostModel, (post) => post.author)
posts: PostModel[];

// Post
@ManyToOne(() => UserModel, (user) => user.posts)
author: UserModel;

ManyToOne에 컬럼 생김, OneToMany의 타입에는 [] 붙여주기

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

 

- ManyToMany

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

// Post
@ManyToMany(() => TagModel, (tag) => tag.posts)
@JoinTable() // JoinTable 있는 곳이 테이블 이름의 앞에 옴.
tags: TagModel[];

테이블이 새로 생김. JoinTable 있는 곳이 테이블 이름의 앞에 옴.

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

 

- Relation Options

@OneToOne(() => ProfileModel, (profile) => profile.user, {
    // find() 실행할 때마다 항상 같이 가져올 relation
    eager: true,
    // 저장할 때 relation의 데이터도 한번에 저장 가능
    cascade: true,
    // null이 가능한지
    nullable: false,
    // 관계가 삭제됐을때
    // no action -> 아무것도 안함
    // cascade: -> 참조하는 Row도 같이 삭제
    // set null -> 참조하는 Row에서 참조 id를 null로 변경
    // set default -> 기본 세팅으로 설정 (테이블의 기본 세팅)
    // restrict -> 참조하는 있는 Row가 있는 경우 참조당하는 Row 삭제 불가
    onDelete: 'RESTRICT',
  })
  profil: ProfileModel;

 

https://www.inflearn.com/course/lecture?courseSlug=nestjs-%EB%B0%B1%EC%97%94%EB%93%9C-%EC%99%84%EC%A0%84%EC%A0%95%EB%B3%B5-%EB%A7%88%EC%8A%A4%ED%84%B0-%ED%81%B4%EB%9E%98%EC%8A%A4-1&unitId=184155&tab=curriculum&category=questionDetail

 

학습 페이지

 

www.inflearn.com

 

728x90

'코딩 > TypeORM' 카테고리의 다른 글

Methods  (0) 2024.10.15
Find Options  (0) 2024.10.15
[Entity] Table Inheritance - 클래스 상속을 이용한 테이블 늘리기  (1) 2024.10.11
Transaction  (0) 2024.04.24
사용 방법 예시들  (0) 2024.04.22