From 84e2c9c6f45802a793547697da2f3f9279509acf Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 20 May 2024 09:05:44 -0500 Subject: [PATCH] Add Override Table Name For Prisma Model as a Prisma TIL --- README.md | 3 +- .../override-table-name-for-prisma-model.md | 42 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 prisma/override-table-name-for-prisma-model.md diff --git a/README.md b/README.md index f0289c5..beb7422 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1432 TILs and counting..._ +_1433 TILs and counting..._ --- @@ -830,6 +830,7 @@ _1432 TILs and counting..._ - [Execute A Raw SQL Query](prisma/execute-a-raw-sql-query.md) - [Grab A Limited Set Of Records](prisma/grab-a-limited-set-of-records.md) - [Open Connections To Multiple Databases](prisma/open-connections-to-multiple-databases.md) +- [Override Table Name For Prisma Model](prisma/override-table-name-for-prisma-model.md) - [Specify Alternate Location For Prisma Schema](prisma/specify-alternate-location-for-prisma-schema.md) ### Python diff --git a/prisma/override-table-name-for-prisma-model.md b/prisma/override-table-name-for-prisma-model.md new file mode 100644 index 0000000..13b2a24 --- /dev/null +++ b/prisma/override-table-name-for-prisma-model.md @@ -0,0 +1,42 @@ +# Override Table Name For Prisma Model + +When defining your Prisma schema, you'll add models to your +`prisma/schema.prisma` file that look something like this: + +``` +model Book { + id BigInt @id @default(autoincrement()) @db.BigInt + title String + author String + publication_year Int + created_at DateTime @default(now()) + updated_at DateTime @updatedAt +} +``` + +The prisma client (ORM-layer) that gets generated will have a `Book` type and +you'll be able to reference the model to, for instance, create a record with +`prisma.book.create(...)`. Both of these things are derived from the model +name: `Book`. + +The other thing that is derived from the model name is the name given to the +underlying database table. So you end up with a table called `Book`. You may, +however, prefer a table naming convention where this one would be named `books` +(snake_case and pluralized). + +To achieve that, you have to manually override the table name with [the `@@map` +directive](https://www.prisma.io/docs/orm/reference/prisma-schema-reference#map-1). +Add it toward the bottom of the model like so: + +``` +model Book { + id BigInt @id @default(autoincrement()) @db.BigInt + title String + author String + publication_year Int + created_at DateTime @default(now()) + updated_at DateTime @updatedAt + + @@map("books") +} +```