Skip to content

Commit 84e2c9c

Browse files
committed
Add Override Table Name For Prisma Model as a Prisma TIL
1 parent 39614e9 commit 84e2c9c

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1432 TILs and counting..._
13+
_1433 TILs and counting..._
1414

1515
---
1616

@@ -830,6 +830,7 @@ _1432 TILs and counting..._
830830
- [Execute A Raw SQL Query](prisma/execute-a-raw-sql-query.md)
831831
- [Grab A Limited Set Of Records](prisma/grab-a-limited-set-of-records.md)
832832
- [Open Connections To Multiple Databases](prisma/open-connections-to-multiple-databases.md)
833+
- [Override Table Name For Prisma Model](prisma/override-table-name-for-prisma-model.md)
833834
- [Specify Alternate Location For Prisma Schema](prisma/specify-alternate-location-for-prisma-schema.md)
834835

835836
### Python
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Override Table Name For Prisma Model
2+
3+
When defining your Prisma schema, you'll add models to your
4+
`prisma/schema.prisma` file that look something like this:
5+
6+
```
7+
model Book {
8+
id BigInt @id @default(autoincrement()) @db.BigInt
9+
title String
10+
author String
11+
publication_year Int
12+
created_at DateTime @default(now())
13+
updated_at DateTime @updatedAt
14+
}
15+
```
16+
17+
The prisma client (ORM-layer) that gets generated will have a `Book` type and
18+
you'll be able to reference the model to, for instance, create a record with
19+
`prisma.book.create(...)`. Both of these things are derived from the model
20+
name: `Book`.
21+
22+
The other thing that is derived from the model name is the name given to the
23+
underlying database table. So you end up with a table called `Book`. You may,
24+
however, prefer a table naming convention where this one would be named `books`
25+
(snake_case and pluralized).
26+
27+
To achieve that, you have to manually override the table name with [the `@@map`
28+
directive](https://www.prisma.io/docs/orm/reference/prisma-schema-reference#map-1).
29+
Add it toward the bottom of the model like so:
30+
31+
```
32+
model Book {
33+
id BigInt @id @default(autoincrement()) @db.BigInt
34+
title String
35+
author String
36+
publication_year Int
37+
created_at DateTime @default(now())
38+
updated_at DateTime @updatedAt
39+
40+
@@map("books")
41+
}
42+
```

0 commit comments

Comments
 (0)