How to define data model in prisma
- User
How to define data model in prisma
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
How to define data model in prisma
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, let's break down how to define a data model in Prisma.
The core of Prisma's data modeling is the Prisma Schema file, typically located at the root of your project in a directory named prisma/ and named schema.prisma. This file uses a declarative, intuitive syntax to describe your database schema, including:
1. The Prisma Schema File (schema.prisma) Structure
// schema.prisma
// Defines the database connection
datasource db {
provider = "postgresql" // e.g., "postgresql", "mysql", "sqlite", "sqlserver", "mongodb"
url = env("DATABASE_URL") // Reads the connection string from environment variables
}
// Configures generators, like Prisma Client
generator client {
provider = "prisma-client-js"
}
// --- Your Models Go Here ---
model User {
// Fields definition...
}
model Post {
// Fields definition...
}
// --- Enums and Composite Types (Optional) ---
enum Role {
ADMIN
USER
MODERATOR
}
2. Defining Models
Models represent your database tables (or collections). You use the model keyword, followed by the model name (PascalCase), and then curly braces {} containing the field definitions.
model User {
id Int @id @default(autoincrement()) // Unique identifier, auto-incrementing integer
email String @unique // Email address, must be unique
name String? // Name is optional (nullable)
role Role @default(USER) // Uses the Role enum, defaults to USER
createdAt DateTime @default(now()) // Timestamp of creation, defaults to current time
updatedAt DateTime @updatedAt // Timestamp automatically updated on record change
// Relations (defined below)
posts Post[] // A User can have multiple Posts
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
authorId Int // Foreign key field (links to User.id)
author User @relation(fields: [authorId], references: [id]) // Relation field linking to User
createdAt DateTime @default(now())
}
3. Defining Fields
Fields represent the columns within your tables. Each field definition has:
fieldName (camelCase convention)@id, @unique, @relation, @default)Common Scalar Field Types:
String: Textual data.Int / BigInt: Whole numbers.Float / Double: Floating-point numbers.Boolean: true or false.DateTime: Date and time values.Json: JSON objects/arrays.Bytes: Raw binary data.Important Attributes:
@id: Marks the field as the primary key for the model. A model must have exactly one primary key.@unique: Enforces uniqueness for the value in this field across all records in the table. You can also define multi-column unique constraints using @@unique([field1, field2]).@default(...): Specifies a default value when creating a record if none is provided. Common defaults include:
autoincrement(): For integer primary keys (specific to SQL databases).now(): Sets the current timestamp (DateTime).uuid(): Generates a UUID (String)."user@example.com", 10, true, etc.@updatedAt: Automatically sets the field to the current timestamp whenever the record is updated (DateTime). Often used with createdAt.@relation(...): Defines or references a relationship between models (see below).@map("db_column_name"): Maps the field name to a different column name in the database (e.g., if your DB uses snake_case like user_id).@@map("db_table_name"): Maps the model name to a different table name in the database.@@id([field1, field2]): Defines a composite primary key spanning multiple fields.@@index([field]): Creates a database index on a field (or multiple fields with @@index([field1, field2])) for faster lookups.4. Defining Relations
Relations link records between different models. Prisma makes this quite declarative:
[] for "to-many" relationships.@relation attribute to specify the connection.Example Relation Scenarios:
One-to-Many (User -> Post):
Post model (the "many" side): authorId Int (the foreign key) and author User @relation(fields: [authorId], references: [id]).User model (the "one" side): posts Post[] (no @relation needed here if defined on the other side, but you can add it for clarity or specific configurations).One-to-One:
User: profile Profile? @relation(onDelete: Cascade) (Optional profile)Profile: userId Int @unique (Unique foreign key) and user User @relation(fields: [userId], references: [id], onDelete: Cascade).onDelete: Cascade means if the User is deleted, their Profile is also deleted. Other options include SetNull, Restrict.Many-to-Many (e.g., Post <-> Tag): Often implemented with an intermediate join table, but Prisma can infer it or you can define it explicitly.
model Post {
// ... other fields
tags Tag[]
}
model Tag {
// ... other fields
posts Post[]
}
(Prisma creates the join table automatically)model Post {
// ... other fields
postTags PostTag[]
}
model Tag {
// ... other fields
postTags PostTag[]
}
model PostTag { // Join table
postId Int @id
tagId Int @id
post Post @relation(fields: [postId], references: [id])
tag Tag @relation(fields: [tagId], references: [id])
}
5. Defining Enums
Enums define a fixed set of allowed string values for a field.
enum Role {
ADMIN
USER
MODERATOR
}
model User {
id Int @id
role Role @default(USER) // Field uses the Role enum
}
Summary
Defining a data model in Prisma involves creating the schema.prisma file, specifying your datasource and generator, and then defining model blocks with fields. Use scalar types for basic data, enums for fixed choices, and the @relation attribute to link models together. Attributes like @id, @unique, and @default are essential for defining constraints and behavior. Once your schema is defined, you run prisma migrate dev to create migrations and update your database, and prisma generate to create the Prisma Client for interacting with your database through your application code.