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 studioprisma studio opens a visual database browser at localhost:5555. It's the fastest way to inspect and edit data during development without writing queries.
