Prisma ORM cheatsheet
Prisma ORM: Schema
4 common Prisma ORM tasks.
Configure the database
Choose the database provider and read the connection string from an environment variable.
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
Define models
A model becomes a table. @id marks the primary key, @default sets defaults and @unique adds a unique index.
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
role Role @default(USER)
posts Post[]
createdAt DateTime @default(now())
}
enum Role {
USER
ADMIN
}
Define a relation
A one-to-many relation uses a foreign key field and a @relation attribute.
model Post {
id Int @id @default(autoincrement())
title String
author User @relation(fields: [authorId], references: [id])
authorId Int
@@index([authorId])
}
Composite keys and unique constraints
Use block attributes for keys and constraints that span several fields.
model Membership {
userId Int
groupId Int
@@id([userId, groupId])
@@unique([groupId, userId])
}