Script Valley
Next.js: Full-Stack React Applications
Database Integration with PrismaLesson 4.2

How to define models and relations in a Prisma schema

model definition, field types, @id, @default, @relation, one-to-many, many-to-many, optional fields, enums, @@index

Defining Models

Prisma models map to database tables. Each field has a type and optional attributes:

// prisma/schema.prisma
model User {
  id        String   @id @default(cuid())
  email     String   @unique
  name      String?
  role      Role     @default(USER)
  posts     Post[]
  createdAt DateTime @default(now())

  @@index([email])
}

enum Role {
  USER
  ADMIN
}

model Post {
  id        String   @id @default(cuid())
  title     String
  content   String?
  published Boolean  @default(false)
  author    User     @relation(fields: [authorId], references: [id])
  authorId  String
  createdAt DateTime @default(now())
}

Key Attributes

@id — primary key. @default(cuid()) — generates a collision-resistant ID. @unique — adds a unique constraint. ? after a type — makes the field optional (nullable). Post[] on User — the relation array (virtual, not a DB column). @relation on Post — declares the foreign key.

Running Migrations

# Development: creates migration file + applies it
npx prisma migrate dev --name add-post-model

# View your DB in a browser
npx prisma studio

prisma studio opens a visual database browser at localhost:5555. It's the fastest way to inspect and edit data during development without writing queries.

Up next

How to perform CRUD operations with Prisma in Next.js

Sign in to track progress