Post

[Nest.js 학습일기] Relationship 이론

[Nest.js 학습일기] Relationship 이론

해당 게시물의 모든 강의 참고자료 출처는 Inflearn - CodeFactory님의 Nest초급강좌 입니다.

Relationship 이론

  • OneToOne, OneToMany, ManyToOne, ManyToMany

OneToOne

말 그대로 하나하나 대응한다는 것임. 유저의 세부 정보를 담은 Table과 유저 아이디와 프로필 이미지를 담고 있는 Table을 생각해보자.

one_to_one

다음의 예시로 이해해보자.

Profile Table

1
2
3
4
5
6
7
8
9
10
11
12
@Entity()
export class ProfileModel {
  @PrimaryGeneratedColumn()
  id: number;

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

  @Column()
  profileImg: string;
}

prpofile.entity.ts에서 user@OneToOne()으로 UserModel과 연결되어있고 UserModel에서 profile이라는 속성으로 관계를 참조함을 의미한다.

또한 @JoinColumn() 으로 profile Table에 외래키 정보가 표시되도록 했음을 알 수 있다.

OneToOne Profile Model Col

User Table

1
2
3
4
5
6
7
8
9
10
11
12
13
@Entity()
export class UserModel {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  email: string;

  // another codes..
  
  @OneToOne(() => ProfileModel, (profile) => profile.user)
  profile: ProfileModel;
}

여기도 마찬가지로 ProfileModel과 연결되어 있고 ProfileModel에선 user이라는 속성으로 관계를 참조함을 알 수 있다.

OneToMany & ManyToOne

한 유저가 여러개의 게시물을 쓸 수 있는 경우를 생각하면 된다.

UserOne, PostMany이므로 UserModel에선 @OneToMany() , PostModel에선 @ManyToOne()

1
2
3
4
5
6
7
8
9
10
11
@Entity()
export class UserModel {
  @PrimaryGeneratedColumn()
  id: number;

  // ..codes..

  // User => Post 이므로 OneToMany
  @OneToMany(() => PostModel, (post) => post.author)
  posts: PostModel;
}
1
2
3
4
5
6
7
8
9
10
11
12
@Entity()
export class PostModel {
  @PrimaryGeneratedColumn()
  id: number;

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

  @Column()
  title: string;
}

근데 이 경우에 ManyToOne()을 사용한 PostModel에만 외래키 참조 칼럼이 형성된다. 이는 typeORM의 기본 동작이다! 자동으로 외래키 칼럼을 Many측에 생성한다.

many_to_one_table

ManyToMany

게시물에 달리는 해시태그를 생각해보자. 하나의 해시태그는 여러개의 게시물에 존재할 수 있고 하나의 게시물에 여러개의 해시태그가 존재할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Entity()
export class PostModel {
  @PrimaryGeneratedColumn()
  id: number;

  // Post 들과 작성자 연결 (Many와 One의 연결)
  @ManyToOne(() => UserModel, (user) => user.posts)
  author: UserModel;

  @ManyToMany(() => TagModel, (tag) => tag.posts)
  @JoinTable()
  tags: TagModel[];

  @Column()
  title: string;
}
1
2
3
4
5
6
7
8
9
10
11
@Entity()
export class TagModel {
  @PrimaryGeneratedColumn()
  id: number;

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

  @Column()
  name: string;
}

@ManyToMany()의 경우 @OneToMany, @ManyToOne과 달리 @JoinTable()이 필요하다.

근데 이 경우 외래키가 그 어떤 테이블에도 생성되지 않는다. 대신 새로운 중간 테이블이 생성된다. 즉, 외래키는 없지만 중간테이블의 외래키들을 통해 관계가 형성된다!

many_to_many_table

This post is licensed under CC BY 4.0 by the author.