본문 바로가기

개발 공부

Prisma 관계(Relation)

Prisma ORM은 단순히 데이터베이스의 테이블을 정의하는 것뿐 아니라, 테이블 간의 관계(Relation)까지 명확하게 코드로 표현할 수 있습니다. 

Relation

데이터베이스에서 관계(Relation)란 두 테이블 간의 연결을 의미합니다. 예를 들어

  • User는 여러 Post를 작성할 수 있다. (1:N 관계)
  • 하나의 Post에는 여러 Comment가 달릴 수 있다. (1:N 관계)
  • 유저가 다른 유저를 팔로우한다. (Self Relation)

Prisma는 이를 모델 코드 안에서 명시적으로 표현할 수 있도록 도와줍니다.

 


 

기본 예시 — User와 Post (1:N 관계)

model User {
  id      String @id @default(cuid())
  name    String
  posts   Post[] // 1:N 관계 (한 명의 유저 → 여러 개의 게시글)
}

model Post {
  id        String @id @default(cuid())
  title     String
  authorId  String

  // Relations
  author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
}

 

  • User는 여러 개의 Post를 작성할 수 있습니다. (posts 배열)
  • Post는 한 명의 User에 의해 작성됩니다. (author 단일 객체)
  • authorId는 User의 id를 참조하는 외래키(Foreign Key) 역할.
  • onDelete: Cascade는 작성자가 삭제되면 해당 작성자의 게시글도 자동으로 삭제되도록 합니다.

관계도

User (1) ───< (N) Post

 

 


 

댓글 구조 — Comment (1:N 관계 중첩)

model Post {
  id       String @id @default(cuid())
  title    String
  comments Comment[] // 게시글은 여러 댓글을 가짐
}

model Comment {
  id      String @id @default(cuid())
  text    String
  postId  String
  post    Post @relation(fields: [postId], references: [id], onDelete: Cascade)
}
  • 하나의 Post에는 여러 Comment가 연결됩니다.

 


자기 참조 관계(Self Relation) — Follows 예시

 

가장 흥미로운 부분은 같은 테이블(User)이 자기 자신을 참조하는 경우입니다.

model User {
  id String @id @default(cuid())
  username String @unique

  // 내가 팔로우하는 사람들
  following Follows[] @relation("follower")
  // 나를 팔로우하는 사람들
  followers Follows[] @relation("following")
}

model Follows {
  followerId  String
  followingId String
  createdAt   DateTime @default(now())

  // Relations
  follower  User @relation("follower",  fields: [followerId],  references: [id], onDelete: Cascade)
  following User @relation("following", fields: [followingId], references: [id], onDelete: Cascade)

  @@id([followerId, followingId]) // 복합 기본키 → 중복 팔로우 방지
}

 

역할 컬럼 설명
팔로우한 사람 followerId User의 id 참조 (나)
팔로우 당한 사람 followingId User의 id 참조 (상대방)\
  • 같은 모델(User)을 두 번 참조하므로 @relation() 안에 관계 이름("follower", "following")을 반드시 지정해야 합니다.
  • Prisma는 이 이름으로 User 모델의 followers/following 필드를 매칭합니다.
  • onDelete: Cascade로 유저 삭제 시 관련 팔로우 기록 자동 삭제.

관계도

User ───< Follows >─── User
 (나)       ↑            (상대방)
 followerId            followingId

 

 

 


 

다대다(N:M) 관계 — Like 예시

Prisma에서는 두 모델이 서로 여러 개를 가질 수 있을 때 중간 테이블(조인 테이블)을 명시적으로 정의합니다.

model User {
  id String @id @default(cuid())
  username String @unique
  likes Like[]
}

model Post {
  id String @id @default(cuid())
  title String
  likes Like[]
}

model Like {
  id        String @id @default(cuid())
  userId    String
  postId    String
  createdAt DateTime @default(now())

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)
  post Post @relation(fields: [postId], references: [id], onDelete: Cascade)

  @@unique([userId, postId]) // 한 유저가 같은 글을 두 번 좋아요하지 못하도록
  @@index([userId, postId]) // 빠른 조회용 인덱스
}
  •  User ↔ Post는 N:M 관계이고, Like가 중간 다리 역할을 합니다.

관계도

User (N) ───< Like >─── (M) Post

 

 


주요 Relation 속성 요약

속성 설명
fields 외래키(FK) 역할을 하는 필드 명시
references 어떤 모델의 어떤 필드를 참조하는지 지정
onDelete: Cascade 참조된 데이터가 삭제되면 연결된 데이터도 함께 삭제
@relation(name) 관계 이름 명시 (특히 자기 참조나 중복 관계에서 필수)

 

 

Prisma에서 관계 조회하기

관계를 정의해두면 include 문법으로 관련 데이터를 손쉽게 불러올 수 있습니다.

const userWithPosts = await prisma.user.findUnique({
  where: { id: 'u1' },
  include: { posts: true },
});

const postWithAuthor = await prisma.post.findUnique({
  where: { id: 'p1' },
  include: { author: true, comments: true },
});

 

 

 


관계 유형 예시 모델 설명
1:N User – Post 한 유저가 여러 글 작성
1:N 중첩 Post – Comment 한 글에 여러 댓글
N:M User – Post (via Like) 좋아요, 태그 등 다대다 관계
Self Relation User – Follows – User 같은 모델 간 팔로우 구조

 

 

 

'개발 공부' 카테고리의 다른 글

Prisma CRUD 예시  (0) 2025.11.12
Prisma DB 연결  (0) 2025.11.09
Prisma 스키마 (2) - 인덱스, 유니크, 복합키  (0) 2025.11.01
Prisma 스키마 (1)  (0) 2025.10.31
Prop Drilling  (0) 2025.10.24