Search code examples
prisma

Use of @map and @@map for Prisma schema


I am new to Prisma and have been wondering what is the use of @map and @@map for Prisma schema? I have looked at their website: https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#map but still don't fully get the purpose of @map and @@map.

From what I can comprehend, if I have something like lastName String @map("last_name") @db.VarChar(256) it maps "last_name" to lastname? But I am not too sure when I will need this.

Thank you! Appreciate any help.


Solution

  • @map can be used to assign a different name to your columns names, for example if the column name for a table in your database is userLastName but you want to assign a different name (user_last_name) and access it with a different name in your generated PrismaClient you can use @map attribute for it.

    model User {
      id        Int    @id @default(autoincrement())
      userLastName String @map("user_last_name")
    }
    
    • @map does not rename the columns / fields in the database
    • @map does change the field names in the generated prisma client

    On the other hand @@map is used to assign a different name to a model and not a particular field. So for example if a table name is UserDetails and you want to access it as user_details in the generated client you can use @@map attribute.

    model UserDetails {
      id   Int    @id @default(autoincrement())
      name String
    
      @@map("users_details")
    }
    

    Edit: TLDR @map helps decouple the name given or defined on the model field from the name defined on the actual database table column. while @@map does same but for model name; it helps you define a different name for your actual database table.