schema.prisma file in Prisma
Here’s how Prisma identifies and utilizes model definitions:
Structure of Prisma Schema
In your schema.prisma
file, you define your database schema using the Prisma schema definition language. This file typically includes:
-
Data Models: Each
model
block defines a database table or collection, along with its fields and relationships. -
Relations:
@relation
directives define relationships between models, such as one-to-one, one-to-many, or many-to-many relationships. -
Datasource: This tells prisma which database to connect to
Example schema.prisma
Here’s a simplified example of a schema.prisma
file with two models (User
and Post
):
// schema.prisma
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
username String
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String
authorId Int
author User @relation(fields: [authorId], references: [id])
}
How Prisma Uses Models
Prisma uses the models defined in your schema.prisma
file to generate a Prisma Client. Here’s how it works:
-
Model Definitions: Each
model
block inschema.prisma
defines a table (or collection) in your database. -
Generated Prisma Client: When you run
npx prisma generate
, Prisma inspects yourschema.prisma
file and generates a TypeScript/JavaScript client (PrismaClient
) based on your model definitions. -
Model Usage in Code:
-
You import and use the generated
PrismaClient
in your Node.js application to interact with your database. For example:const { PrismaClient } = require('@prisma/client'); const prisma = new PrismaClient(); async function createUser(username) { const user = await prisma.user.create({ data: { username, }, }); return user; }
Here,
prisma.user
refers to theUser
model defined in yourschema.prisma
.
-
-
Naming Convention: Prisma expects the name of the model in your Prisma schema to match the corresponding table (or collection) name in your database. This convention ensures that Prisma can correctly map operations to the appropriate database entities.