Prisma ORM Guide
Schema Definition
// schema.prisma
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[]
profile Profile?
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
tags Tag[]
}
model Tag {
id Int @id @default(autoincrement())
name String @unique
posts Post[]
}
Queries
const prisma = new PrismaClient();
// Find
const users = await prisma.user.findMany({
where: { email: { contains: '@example.com' } },
orderBy: { createdAt: 'desc' },
take: 10, skip: 0,
include: { posts: { where: { published: true } } },
});
// Create
const user = await prisma.user.create({
data: {
email: 'alice@example.com',
name: 'Alice',
posts: { create: { title: 'First post' } },
},
});
// Update
await prisma.post.update({ where: { id: 1 }, data: { published: true } });
// Delete
await prisma.user.delete({ where: { id: 1 } });
// Upsert
await prisma.user.upsert({
where: { email: 'alice@example.com' },
update: { name: 'Alice Smith' },
create: { email: 'alice@example.com', name: 'Alice Smith' },
});
CLI Commands
| Command | Description |
|---|---|
| npx prisma init | Initialize Prisma |
| npx prisma generate | Generate client |
| npx prisma migrate dev | Create and apply migration |
| npx prisma migrate deploy | Apply migrations in prod |
| npx prisma db push | Push schema without migration |
| npx prisma studio | Open DB browser |
| npx prisma db seed | Run seed script |