Getting Started with Prisma ORM
Prisma is my favorite way to work with databases in TypeScript projects. It gives you a type-safe query API that's both intuitive and powerful.
Setup
npm install prisma @prisma/client
npx prisma init
Defining Your Schema
model User {
id String @id @default(cuid())
email String @unique
name String?
posts Post[]
createdAt DateTime @default(now())
}
model Post {
id String @id @default(cuid())
title String
content String @db.Text
author User @relation(fields: [authorId], references: [id])
authorId String
published Boolean @default(false)
}
Running Migrations
npx prisma migrate dev --name init
Querying
const posts = await prisma.post.findMany({
where: { published: true },
include: { author: true },
orderBy: { createdAt: 'desc' },
})
Prisma's query API is incredibly readable and the TypeScript types are automatically inferred.