Define Prisma data models, datasources, generators, enums, and relations in schema.prisma. Use when creating or modifying a Prisma schema file, adding models/fields/enums, or configuring database connections.
Define your data model in prisma/schema.prisma — the single source of truth for your database structure.
prisma/schema.prismadatasource block with provider and connection URLgenerator block (usually prisma-client-js)@relation@@index for query performancenpx prisma validatenpx prisma formatnpx prisma migrate dev --name <name> or npx prisma db pushdatasource 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?
role Role @default(USER)
posts Post[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
createdAt DateTime @default(now())
@@index([authorId])
}
enum Role {
USER
ADMIN
}
Modifiers: ? = optional/nullable, [] = list/array
@id — primary key@unique — unique constraint@default(value) — default: autoincrement(), uuid(), cuid(), now(), dbgenerated("expr")@updatedAt — auto-updates on every save@relation(fields: [fk], references: [pk]) — define foreign key relation@map("column_name") — custom column name in DB@db.VarChar(255) — native type annotation@@id([field1, field2]) — composite primary key@@unique([field1, field2]) — composite unique constraint@@index([field1, field2]) — database index@@map("table_name") — custom table name in DBmodel User {
posts Post[]
}
model Post {
author User @relation(fields: [authorId], references: [id])
authorId Int
}
model User {
profile Profile?
}
model Profile {
user User @relation(fields: [userId], references: [id])
userId Int @unique
}
model Post { tags Tag[] }
model Tag { posts Post[] }
model Employee {
id Int @id @default(autoincrement())
manager Employee? @relation("Management", fields: [managerId], references: [id])
managerId Int?
subordinates Employee[] @relation("Management")
}
On @relation: onDelete: Cascade | Restrict | NoAction | SetNull | SetDefault
model Post {
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
authorId Int
}
datasource block is allowed per schema@unique on a relation scalar field makes the relation one-to-one@map("_id") on the id field and @db.ObjectId for ObjectId types@@id) cannot use autoincrement()@updatedAt only works on DateTime fieldsJson type is not available on SQLite