Nest.js - One to Many / Many to One

크롱·2024년 10월 24일
0

Nest.js

목록 보기
8/15

한명의 user는 많은 post 를 가질 수 있다
userone to many relationship with the post
주체 엔티티 user가 하나이므로 one to many!

반대로 postmany to one relationship with the user.
많은 post들이 하나의 user(author)을 갖기 때문이다

user와 Post 처럼, many to one and one to many 인 경우 양방향이라고 보며 many to one and one to many는 보통 항상 함께 존재한다.

in case of many to one and one to many relationship, we will consider it as a bidirectional relationship. So we look at one to many and many to one relationships as a case of a bidirectional relationship between two entities.

  • foreign key 는 항상 many to one 쪽에 위치한다. join컬럼은 필요없다
    -> 즉, post 테이블에 author(user) foreign key Id 있음

실습

양방향 One to one 일때랑 비슷함.

Many to One

import {
  Entity,
  ManyToOne,
} from 'typeorm';
import { User } from 'src/users/user.entity';

@Entity()
export class Post {
  
  ...

  @ManyToOne(() => User, (user) => user.posts) // foreign key 존재
  author: User;


}

One to Many

import { Post } from 'src/posts/post.entity';
import { Entity, OneToMany } from 'typeorm';

@Entity()
export class User {
  ...
  @OneToMany(() => Post, (post) => post.author)
  posts: Post[];

}
profile
👩‍💻안녕하세요🌞

0개의 댓글