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

CommandDescription
npx prisma initInitialize Prisma
npx prisma generateGenerate client
npx prisma migrate devCreate and apply migration
npx prisma migrate deployApply migrations in prod
npx prisma db pushPush schema without migration
npx prisma studioOpen DB browser
npx prisma db seedRun seed script