본문 바로가기
TIL

Nodejs 강의 숙련 게시판 프로젝트(4) prisma

by 황민도 2024. 5. 23.

내일배움캠프 스파르타 코딩클럽

 

숙련 1주차 강의 프로젝트 게시판을 만들며 하나하나 코드를 정의하는 법을 보도록 하겠다.

 

< schema.prisma >

사용자 Users 테이블과 사용자 정보 UserInfos 테이블 1:1 관계 설정 

model Users {
  userId Int @id @default(autoincrement()) @map("userId")
  email String @unique @map("email")
  password String @map("password")

  createdAt DateTime @default(now()) @map("createdAt")
  updatedAt DateTime @updatedAt @map("updatedAt")

  UserInfos UserInfos?
  // 사용자(Users) 테이블과 사용자 정보(UserInfos) 테이블이 1:1

  @@map("Users")
}

 

 

model UserInfos {
  userInfoId Int @id @default(autoincrement()) @map("userInfoId")
  UserId Int @unique @map("UserId")
  name String @map("name")
  age Int? @map("age") 
  // null을 허용 할때는 ? 를 사용 , Optional Parameter(?)
  gender String @map("gender")
  profileImage String? @map("profileImage")

  createdAt DateTime @default(now()) @map("createdAt")
  updatedAt DateTime @updatedAt @map("updatedAt")

  User Users @relation(fields: [UserId], references: [userId], onDelete: Cascade)
  // Users 테이블과 관계를 설정합니다.
  // 무결성 제약조건 사용자가 삭제된다면 사용자 정보 또한 같이 삭제되도록 Cascade 설정
  // onDelete | onUpdate 참조하는 부모모델이 삭제 or 수정될 경우 자식모델이 어떤행위를 할 지 설정합니다.

  @@map("UserInfos")
}

 

User 필드 값이 나타내는 코드 해석

  • @relation: 이 데코레이터는 두 모델 간의 관계를 정의한다.
  • fields: [UserId]: UsersInfos 모델의 컬럼 중 UserId 필드가 관계를 정의하는 데 사용된다.
    즉, Users 모델의 UserId 필드는 외래 키이다.
  • references: [userId]: Users 모델의 userId 필드가 참조된다.
    즉, UsersInfos 모델의 UserId 필드는 Users 모델의 userId 필드를 가리킨다.

 

 

< schema.prisma >

사용자 Users 테이블과 게시글 Posts 테이블이 1:N 관계 설정

model Users {
  userId Int @id @default(autoincrement()) @map("userId")
  email String @unique @map("email")
  password String @map("password")

  createdAt DateTime @default(now()) @map("createdAt")
  updatedAt DateTime @updatedAt @map("updatedAt")

  UserInfos UserInfos?
  // 사용자(Users) 테이블과 사용자 정보(UserInfos) 테이블이 1:1
  // 1명의 사용자는 1개의 사용자 정보를 가진다.
  Posts Posts[]
  // 사용자(Users) 테이블과 게시글(Posts) 테이블이 1:N
  // 1명의 사용자는 여러개의 게시글을 작성할 수 있다. (배열사용)

  @@map("Users")
}

위와 같이 N인 Posts 테이블을 배열사용

model Posts {
  postId Int @id default(autoincrement()) @map("postId")
  UserId Int @map("UserId")
  // 사용자(Users) 테이블을 참조하는 외래키
  title String @map("title")
  content String @db.Text @map("content") 
  // @db.Text 긴 텍스트 사용시, 텍스트 데이터를 효율적으로 저장하고 사용할 수 있음.
  createdAt DateTime @default(now()) @map("createdAt")
  updatedAt DateTime @updatedAt @map("updatedAt")

  User Users @relation(fields: [UserId], references: [userId], onDelete: Cascade)
  // Users 테이블 관계를 설정합니다.

  @@map("Posts")
}

여러개를 가지므로 UserId 에 @unique 데코레이터 미사용

 

< schema.prisma >

사용자 Users 테이블, 게시글 Posts 테이블을 댓글 Comments 테이블과 1:N 관계 설정 (둘다 참조)

model Users {
  userId Int @id @default(autoincrement()) @map("userId")
  email String @unique @map("email")
  password String @map("password")

  createdAt DateTime @default(now()) @map("createdAt")
  updatedAt DateTime @updatedAt @map("updatedAt")

  UserInfos UserInfos?
  // 사용자(Users) 테이블과 사용자 정보(UserInfos) 테이블이 1:1
  // 1명의 사용자는 1개의 사용자 정보를 가진다.
  Posts Posts[]
  // 사용자(Users) 테이블과 게시글(Posts) 테이블이 1:N
  // 1명의 사용자는 여러개의 게시글을 작성할 수 있다. (배열사용)
  Comments Comments[]
  // 1명의 사용자는 여러개의 댓글을 작성할 수 있다. (배열사용)

  @@map("Users")
}

위와 같이 N인 Comments 테이블을 배열사용

model Posts {
  postId Int @id @default(autoincrement()) @map("postId")
  UserId Int @map("UserId")
  // 사용자(Users) 테이블을 참조하는 외래키
  title String @map("title")
  content String @db.Text @map("content") 
  // @db.Text 긴 텍스트 사용시, 텍스트 데이터를 효율적으로 저장하고 사용할 수 있음.
  createdAt DateTime @default(now()) @map("createdAt")
  updatedAt DateTime @updatedAt @map("updatedAt")

  User Users @relation(fields: [UserId], references: [userId], onDelete: Cascade)
  // Users 테이블 관계를 설정합니다.
  Comments Comments[]
  // 1개의 게시글에서 여러개의 댓글을 작성할 수 있다.

  @@map("Posts")
}

위와 같이 N인 Comments 테이블을 배열사용

model Comments {
  commentId Int @id @default(autoincrement()) @map("commentId")
  UserId Int @map("UserId")
  PostId Int @map("PostId")
  content String @map("content")

  createdAt DateTime @default(now()) @map("createdAt")
  updatedAt DateTime @updatedAt @map("updatedAt")

  User Users @relation(fields: [UserId], references: [userId], onDelete: Cascade)
  Post Posts @relation(fields: [PostId], references: [postId], onDelete: Cascade)

  @@map("Comments")
}

Users 테이블 Posts 테이블 모두 관계설정

 

이렇게 prisma schema설정을 완료 해주면

다음과 같이 .env 파일에서 사용할 데이터베이스를 설정해준다.

# Environment variables declared in this file are automatically made available to Prisma.
# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema

# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings

DATABASE_URL="mysql://root:aaaa0000@express-database.cncyamsii5xq.ap-northeast-2.rds.amazonaws.com:3306/community_hub"

 

그리고 mysql을 사용할 것이기 때문에

< shema.prisma >

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

이렇게 기본설정이 되어있다면

 

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

이렇게 provider 를 mysql로 변경해준다.

모두 완료가 되었다면

npx prisma db push

(실제 데이터 베이스를 mysql에 upload해 준다.)

Users 테이블을 먼저 확인해보면

실제 컬럼 외 UserInfos? Posts[] Comments[] 는 프리즈마가 인식할 수 있도록 만들어진 문법이라 나타내진 않는다.

 

UserId 연관관계를 맺고있는 UserId 가 정의된 것을 확인 할 수 있다. type 과 데코레이터 map 등으로 구현하였기 때문 실제 컬럼에서도 확인 가능

여기서 UserId key UNI: unique 를 뜻함.

여기서 UserId key MUL: Multiple 을 뜻함.

 

다음은 숙련 강의 2주차 로 넘어가서 이어 게시판 프로젝트를 진행해 보도록 하겠다.