티스토리 뷰

RDBMS/Prisma

@relation attribute

James Wetzel 2025. 5. 21. 16:03

To set up relations in your Prisma schema, you define connections between models using relation fields and the @relation attribute. Here’s how you can do it for the main types of relations:

1. One-to-Many Relation

For example, a User can have many Posts, but each Post has only one User as its author:

model User {  
  id    Int    @id @default(autoincrement())  
  posts Post[]  
}

model Post {  
  id       Int  @id @default(autoincrement())  
  author   User @relation(fields: [authorId], references: [id])  
  authorId Int  
  title    String
}
  • The posts field in User and the author field in Post are relation fields.
  • The authorId field in Post is a relation scalar field (the foreign key) and is referenced in the @relation attribute.
    Learn more

2. One-to-One Relation

A User can have one Profile, and each Profile belongs to one User:

model User {  
  id      Int      @id @default(autoincrement())  
  profile Profile?  
}

model Profile {  
  id     Int  @id @default(autoincrement())  
  user   User @relation(fields: [userId], references: [id])  
  userId Int  @unique
}
  • The userId field in Profile is marked as @unique to enforce the one-to-one relationship.
    See details

3. Many-to-Many Relation

For example, a Post can have many Category entries, and a Category can have many Posts:

model Post {  
  id         Int        @id @default(autoincrement())  
  categories Category[]  
}

model Category {  
  id    Int    @id @default(autoincrement())  
  posts Post[]  
}
  • This is an implicit many-to-many relation; Prisma manages the join table for you.
    More info

General Notes

  • Use the @relation attribute to specify which fields are used for the relation and which fields they reference.
  • Relation fields (like posts, author, profile) exist only in the Prisma schema and Prisma Client, not in the database.
  • Relation scalar fields (like authorId, userId) are the actual foreign keys in your database.
  • For databases that do not support foreign keys (like MongoDB or PlanetScale without FKs), you may need to use the relationMode = "prisma" option in your datasource block.
    Read about relation modes

If you introspect an existing database, Prisma will attempt to infer relations based on foreign keys and unique constraints it finds in your schema.
See introspection details

For more advanced scenarios, such as disambiguating multiple relations between the same models or using composite keys, refer to the relations documentation.

728x90
반응형