11.5 Related Products

7494 ワード

関連トピック機能の実装


1.USSWR入力

import { Product, User } from '@prisma/client' // db 테이블의 타입을 prisma에서 생성해준 것을 사용할 수 있음

// product에 user 정보를 포함했기 때문에 별도의 타입이 필요함
// type ProductDetailResponse = { 
//  ok: boolean;
//  product: Product
// }

// interface를 사용할 때는 extneds를 통해 생성함
type ProductWithUser = { 
  ok: boolean;
  product: Product & { user: User }
}

const { data } = useSWR<ProductWithUser>()...;

2.realtedProductクエリーコマンドの作成


OR: One or more conditions must return true
// post의 title이 Prisma 이거나 databases이 포함된 것을 조회하여 return 함
// OR에 [ ]을 넣어주면 관련 키워드를 지닌 값을 리턴하도록 응용
const result = await prisma.post.findMany({
  where: {
    OR: [
      {
        title: {
          contains: 'Prisma',
        },
      },
      {
        title: {
          contains: 'databases',
        },
      },
    ],
  },
})
このアイテムの名称から関連アイテムを検索するキーワードを生成する.prismaのfilter apiを使用して、次の配列形式を生成します.アイテム名が「galaxys 60」の場合、splitを使用して配列が生成されます.
// 관련 항목 검색어 추출

const itemName = '갤럭시 s60';
const terms = itemName.split(" ").map(word => ({
  name: {
    contains : {
      word
    }
  }
}))
// [{name: containes: { word: '갤럭시' }}, {name: containes: { word: 's60' }}]

const relatedProducts = client.product.findMany({
  where: {
    OR: terms,
  }
});

// 그리고 생성된 배열을 위와 같이 삽입
クエリーの成果物

次に、現在の投稿を関連項目でクエリーしないように処理します.ORとAND接続条件を使用し、NOTを使用して~이 아닌条件を設定します.
const relatedProducts = client.product.findMany({
  where: {
    OR: terms,
    AND: {
      id: {
        not: product?.id,
      }
    }
  }
});