[TIL] Day 47 : Compound Unique Input 으로 조회하기

Q·2024년 6월 20일

TIL

목록 보기
48/59

Compound Unique Input

schema.prisma의 model에서 설정한 composite unique constraint를 바탕으로 findUnique 검색을 할 수 있다.
fieldName1fieldName2 을 합쳐서 composite unique constraint 설정이 되어있다면, fieldName1_fieldName2 이렇게 언더바(_)로 field 이름을 묶은 변수명이 compound unique input의 이름이 된다.

예시

// schema.prisma

model Like {
  id         Int        @id @default(autoincrement())
  customerId Int        @map("customer_id")
  storeId    Int        @map("store_id")
  createdAt  DateTime   @default(now()) @map("created_at")
  updatedAt  DateTime   @updatedAt @map("updated_at")

  customer   User       @relation(fields: [customerId], references: [id], onDelete: Cascade)
  store      Store      @relation(fields: [storeId], references: [id], onDelete: Cascade)

  @@unique([customerId, storeId])
  @@map("likes")
}

// like.repository.js 의 method

like = async (customerId, storeId, { tx } = {}) => {
    const orm = tx || this.prisma;
    await orm.like.create({ data: { customerId, storeId } });
  };

unlike = async (customerId, storeId, { tx } = {}) => {
    const orm = tx || this.prisma;
    await orm.like.delete({
      where: { customerId_storeId: { customerId, storeId } },
  });
};

0개의 댓글