Home   prisma  

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:

  1. Data Models: Each model block defines a database table or collection, along with its fields and relationships.

  2. Relations: @relation directives define relationships between models, such as one-to-one, one-to-many, or many-to-many relationships.

  3. 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:

  1. Model Definitions: Each model block in schema.prisma defines a table (or collection) in your database.

  2. Generated Prisma Client: When you run npx prisma generate, Prisma inspects your schema.prisma file and generates a TypeScript/JavaScript client (PrismaClient) based on your model definitions.

  3. 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: {
        return user;

      Here, prisma.user refers to the User model defined in your schema.prisma.

  4. 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.

Published on: Jul 10, 2024, 12:42 AM  


Add your comment