npm install prisma --save-dev
npx prisma init
npm install @prisma/client
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
createdAt DateTime @default(now())
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
author User @relation(fields: [authorId], references: [id])
authorId Int
createdAt DateTime @default(now())
}
npx prisma migrate dev --name init
npx prisma migrate deploy
npx prisma migrate reset
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
const user = await prisma.user.findUnique({
where: { id: 1 },
})
const users = await prisma.user.findMany()
const newUser = await prisma.user.create({
data: {
email: 'user@example.com',
name: 'John Doe',
},
})
const updatedUser = await prisma.user.update({
where: { id: 1 },
data: { name: 'Jane Doe' },
})
const deletedUser = await prisma.user.delete({
where: { id: 1 },
})
const postWithAuthor = await prisma.post.findMany({
include: { author: true },
})
const newPost = await prisma.post.create({
data: {
title: 'My First Post',
content: 'Hello World',
author: {
connect: { id: 1 }
}
}
})
const updatedPost = await prisma.post.update({
where: { id: 1 },
data: {
content: 'Updated Content',
author: {
update: { name: 'New Author' }
}
}
})
npx prisma generate
npx prisma studio
const users = await prisma.user.findMany({
where: { email: 'user@example.com' }
})
const users = await prisma.user.findMany({
where: {
OR: [{ name: 'John' }, { email: 'john@example.com' }]
}
})
const users = await prisma.user.findMany({
where: {
AND: [{ name: 'John' }, { email: 'john@example.com' }]
}
})
const users = await prisma.user.findMany({
orderBy: { createdAt: 'desc' }
})
const users = await prisma.user.findMany({
skip: 10,
take: 5
})
This cheatsheet should give you a solid reference for using Prisma in your project. If you need more advanced operations or specific examples, feel free to ask!