prisma 에서 두개의 테이블을 연결하기 (외래키)

gak·2023년 4월 8일
0

두개의 테이블을 연결하기.

먼저 Post 라는 model 의 데이터타입을 만들었다.
id 는 정수형이며, 자동으로 증가하는 형태이다.
title 과 content 는 String 타입이며, 해당 값은 널이 될 수 없다. (! 가 들어가면 널이 들어올 수 없다는 뜻이다.)
또한 published 는 해당 게시물이 출판되었는지 확인하는 용도로, 만약에 유저가 포스트를 작성하고 출판하지 않았다면, (e.g. 임시저장) 해당 값은 False 가 된다.

model Post {
      id: Int @default(autoincrement()) @id
      title: String!
      content: String!
      published: Boolean! @default(value: false)
}

이제 여기서 만든 Post 라는 model 을 User 에 연결시켜야 한다.
왜냐하면 글쓴이가 누구인지 알아야하기 때문이다.

이때 prisma 의 relation 을 사용한다.

model User {
  id    Int    @id @default(autoincrement())
  posts Post[]
}

model Post {
  id       Int  @id @default(autoincrement())
  author   User @relation(fields: [authorId], references: [id])
  authorId Int // relation scalar field  (used in the `@relation` attribute above)
}

@relation 은 다른 테이블과 현재 테이블의 연결을 만들어주며, 위 예시에서는 authorId 가 외래키로 작동한다.

A foreign key is a column or group of columns in a relational database table that refers to the primary key or unique key of another table. It is a way to establish a relationship between two tables in a relational database.

즉, Post Model 에 존재하는 foreign key 인 authorId 는 User 모델의 primary key 인 id 를 나타내기 때문에 외래키인것이다.

profile
Hello. I'm Front-End Developer Trying to Create Valuable Things.

0개의 댓글