Prisma CRUD

젤리·2023년 9월 1일
post-thumbnail

Create

보통 post방식으로 진행

create()

한 개의 데이터만 추가하기

const user = await prisma.user.create({
  data: {
    email: 'elsa@prisma.io',
    name: 'Elsa Prisma',
  },
})

createMany()

데이터 여러개 한 번에 생성하기
skipDuplicatestrue로 해주면 중복 데이터가 생성되는 것을 막을 수 있음!

const createMany = await prisma.user.createMany({
  data: [
    { name: 'Bob', email: 'bob@prisma.io' },
    { name: 'Bobo', email: 'bob@prisma.io' }, // Duplicate unique key!
    { name: 'Yewande', email: 'yewande@prisma.io' },
    { name: 'Angelique', email: 'angelique@prisma.io' },
  ],
  skipDuplicates: true, // Skip 'Bobo'
})

Read

보통 get방식으로 진행

findUnique()

Get record by ID or unique identifier

// By unique identifier
const user = await prisma.user.findUnique({
  where: {
    email: 'elsa@prisma.io',
  },
})

// By ID
const user = await prisma.user.findUnique({
  where: {
    id: 99,
  },
})

findMany()

Get all records
리스트 뽑을 때 많이 사용
select * from user 랑 같은 결과값이 나오는 것 같음

const users = await prisma.user.findMany()

findFirst()

Get the first record that matches a specific criteria
특정 기준과 일치하는 첫번째 record 출력

다음은 id를 내림차순으로 user을 정렬하고, 좋아요가 100 이상인 게시물(최소 1개 이상 있는) 중 가장 첫번째 글을 출력하는 코드

const findUser = await prisma.user.findFirst({
    where: {
      posts: {
        some: {
          likes: {
            gt: 100
          }
        }
      }
    },
    orderBy: {
      id: "desc"
    }
  })
}

하지만 이런식으로 가벼운 조건을 주고도 출력이 되기는 합니다.

 await client.user.findFirst({
            where: {
                name: '11',
            },
        });

Update

보통 put방식으로 진행

update()

Update a single record
emailviola@prisma.io인 사람의 이름을 Viola the Magnificent로 바꾼다!

const updateUser = await prisma.user.update({
  where: {
    email: 'viola@prisma.io',
  },
  data: {
    name: 'Viola the Magnificent',
  },
})

updateMany()

Update multiple records
phonea123인 사람들의 이름을 321로 바꾼다

await prisma.user.updateMany({
  where: {
    phone: 'a123',
  },
  data: {
   name: '321',
 },
});

upsert()

Update or create records
emailviola@prisma.io인 사람의 이름을 Viola the Magnificent로 바꾼다! 만약 user에 존재하지 않을 경우 create해준다!

const upsertUser = await prisma.user.upsert({
  where: {
    email: 'viola@prisma.io',
  },
  update: {
    name: 'Viola the Magnificent',
  },
  create: {
    email: 'viola@prisma.io',
    name: 'Viola the Magnificent',
  },
})

Delete

보통 delete방식으로 진행

delete()

Delete a single record

const deleteUser = await prisma.user.delete({
  where: {
    email: 'bert@prisma.io',
  },
})

deleteMany()

Delete multiple records
user테이블 emailprisma.io를 포함하는 모든 레코드를 삭제한다!

const deleteUsers = await prisma.user.deleteMany({
  where: {
    email: {
      contains: 'prisma.io',
    },
  },
})

참고한 Prisma 공식문서
https://www.prisma.io/docs/concepts/components/prisma-client/crud

profile
우젤리젤리

0개의 댓글