All Resources
Framework
DatabaseORMTypeScript
May 26, 2024

Prisma ORM Patterns

Modern database access with Prisma - type-safe database queries and migrations.

Overview

Prisma is a next-generation ORM that provides type-safe database access, intuitive data modeling, and automated migrations.

Key Features

  • Type Safety: Fully generated types from schema
  • Auto Migrations: Create and manage migrations automatically
  • Studio: Visual database explorer
  • Relations: Simplified relationship handling
  • Aggregate Queries: Count, sum, average operations

Quick Start

npm install @prisma/client
npx prisma init

Schema Definition

// prisma/schema.prisma
model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

model Post {
  id    Int   @id @default(autoincrement())
  title String
  user  User  @relation(fields: [userId], references: [id])
  userId Int
}

Database Operations

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

// Create
const user = await prisma.user.create({
  data: { email: 'alice@example.com', name: 'Alice' }
})

// Read
const posts = await prisma.post.findMany({
  where: { user: { email: 'alice@example.com' } },
  include: { user: true }
})

// Update
await prisma.user.update({
  where: { id: 1 },
  data: { name: 'Bob' }
})

// Delete
await prisma.user.delete({ where: { id: 1 } })

Prisma's migration system handles complex schema changes safely.

Curated by

Shyam