보통 post방식으로 진행
한 개의 데이터만 추가하기
const user = await prisma.user.create({
data: {
email: 'elsa@prisma.io',
name: 'Elsa Prisma',
},
})
데이터 여러개 한 번에 생성하기
skipDuplicates를 true로 해주면 중복 데이터가 생성되는 것을 막을 수 있음!
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'
})
보통 get방식으로 진행
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,
},
})
Get all records
리스트 뽑을 때 많이 사용
select * from user 랑 같은 결과값이 나오는 것 같음
const users = await prisma.user.findMany()
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',
},
});
보통 put방식으로 진행
Update a single record
email이 viola@prisma.io인 사람의 이름을 Viola the Magnificent로 바꾼다!
const updateUser = await prisma.user.update({
where: {
email: 'viola@prisma.io',
},
data: {
name: 'Viola the Magnificent',
},
})
Update multiple records
phone이 a123인 사람들의 이름을 321로 바꾼다
await prisma.user.updateMany({
where: {
phone: 'a123',
},
data: {
name: '321',
},
});
Update or create records
email이 viola@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 a single record
const deleteUser = await prisma.user.delete({
where: {
email: 'bert@prisma.io',
},
})
Delete multiple records
user테이블 email에 prisma.io를 포함하는 모든 레코드를 삭제한다!
const deleteUsers = await prisma.user.deleteMany({
where: {
email: {
contains: 'prisma.io',
},
},
})
참고한 Prisma 공식문서
https://www.prisma.io/docs/concepts/components/prisma-client/crud