跳到主要內容

內省

使用 Prisma ORM 內省您的資料庫

為了本指南的目的,我們將使用一個包含三個表格的示範 SQL Schema

CREATE TABLE "public"."User" (
id SERIAL PRIMARY KEY NOT NULL,
name VARCHAR(255),
email VARCHAR(255) UNIQUE NOT NULL
);

CREATE TABLE "public"."Post" (
id SERIAL PRIMARY KEY NOT NULL,
title VARCHAR(255) NOT NULL,
"createdAt" TIMESTAMP NOT NULL DEFAULT now(),
content TEXT,
published BOOLEAN NOT NULL DEFAULT false,
"authorId" INTEGER NOT NULL,
FOREIGN KEY ("authorId") REFERENCES "public"."User"(id)
);

CREATE TABLE "public"."Profile" (
id SERIAL PRIMARY KEY NOT NULL,
bio TEXT,
"userId" INTEGER UNIQUE NOT NULL,
FOREIGN KEY ("userId") REFERENCES "public"."User"(id)
);

注意:有些欄位使用雙引號括起來,以確保 PostgreSQL 使用正確的大小寫。如果沒有使用雙引號,PostgreSQL 會將所有內容讀取為小寫字元。

展開以查看表格的圖形化概觀

User

欄位名稱類型主鍵外鍵必填預設值
idSERIAL✔️✔️自動遞增
nameVARCHAR(255)-
emailVARCHAR(255)✔️-

Post

欄位名稱類型主鍵外鍵必填預設值
idSERIAL✔️✔️自動遞增
createdAtTIMESTAMP✔️now()
titleVARCHAR(255)✔️-
contentTEXT-
publishedBOOLEAN✔️false
authorIdINTEGER✔️✔️-

Profile

欄位名稱類型主鍵外鍵必填預設值
idSERIAL✔️✔️自動遞增
bioTEXT-
userIdINTEGER✔️✔️-

下一步,您將內省您的資料庫。內省的結果將會是 Prisma Schema 內的資料模型

執行以下命令以內省您的資料庫

npx prisma db pull

此命令會讀取在 .env 中定義的 DATABASE_URL 環境變數,並連線到您的資料庫。一旦連線建立,它會內省資料庫(即讀取資料庫 Schema)。然後,它會將資料庫 Schema 從 SQL 轉換為 Prisma Schema 中的資料模型。

內省完成後,您的 Prisma Schema 將會更新

Introspect your database with Prisma ORM

資料模型現在看起來會像這樣(請注意,模型上的欄位為了更好的可讀性而被重新排序)

prisma/schema.prisma
model Post {
id Int @id @default(autoincrement())
title String @db.VarChar(255)
createdAt DateTime @default(now()) @db.Timestamp(6)
content String?
published Boolean @default(false)
authorId Int
User User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction)
}

model Profile {
id Int @id @default(autoincrement())
bio String?
userId Int @unique
User User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction)
}

model User {
id Int @id @default(autoincrement())
name String? @db.VarChar(255)
email String @unique @db.VarChar(255)
Post Post[]
Profile Profile?
}

Prisma ORM 的資料模型是您的資料庫 Schema 的宣告式表示,並作為產生的 Prisma Client 程式庫的基礎。您的 Prisma Client 實例將公開針對這些模型量身定制的查詢。

目前,資料模型存在一些小的「問題」

  • User 關聯欄位是大寫的,因此不符合 Prisma 的命名慣例。為了表達更多「語義」,如果這個欄位被稱為 author 以更好地描述 UserPost 之間的關係,那就更好了。
  • User 上的 PostProfile 關聯欄位,以及 Profile 上的 User 關聯欄位都是大寫的。為了符合 Prisma 的命名慣例,這兩個欄位都應該小寫為 postprofileuser
  • 即使在小寫之後,User 上的 post 欄位仍然略有命名不當。那是因為它實際上指的是一個 posts 列表 – 因此更好的名稱應該是複數形式:posts

這些變更與產生的 Prisma Client API 相關,其中使用小寫的關聯欄位 authorpostsprofileuser 對於 JavaScript/TypeScript 開發人員來說會感覺更自然和慣用。因此,您可以設定您的 Prisma Client API

由於關聯欄位虛擬的(即它們不會直接在資料庫中顯現),因此您可以手動在您的 Prisma Schema 中重新命名它們,而無需觸及資料庫

prisma/schema.prisma
model Post {
id Int @id @default(autoincrement())
title String @db.VarChar(255)
createdAt DateTime @default(now()) @db.Timestamp(6)
content String?
published Boolean @default(false)
authorId Int
author User @relation(fields: [authorId], references: [id], onDelete: NoAction, onUpdate: NoAction)
}

model Profile {
id Int @id @default(autoincrement())
bio String?
userId Int @unique
user User @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction)
}

model User {
id Int @id @default(autoincrement())
name String? @db.VarChar(255)
email String @unique @db.VarChar(255)
posts Post[]
profile Profile?
}

在本範例中,資料庫 Schema 確實遵循了 Prisma ORM 模型的命名慣例(只有從內省產生的虛擬關聯欄位不符合它們,需要調整)。這優化了產生的 Prisma Client API 的人體工學。

使用自訂模型和欄位名稱

但有時,您可能希望對 Prisma Client API 中公開的欄位和表格名稱進行額外變更。一個常見的範例是轉換 snake_case 表示法(通常在資料庫 Schema 中使用)為 PascalCasecamelCase 表示法,這對於 JavaScript/TypeScript 開發人員來說感覺更自然。

假設您從內省中獲得了以下模型,該模型基於 snake_case 表示法

model my_user {
user_id Int @id @default(autoincrement())
first_name String?
last_name String @unique
}

如果您為此模型產生了 Prisma Client API,它將在其 API 中採用 snake_case 表示法

const user = await prisma.my_user.create({
data: {
first_name: 'Alice',
last_name: 'Smith',
},
})

如果您不想在您的 Prisma Client API 中使用資料庫中的表格和欄位名稱,您可以使用 @map@@map 來設定它們

model MyUser {
userId Int @id @default(autoincrement()) @map("user_id")
firstName String? @map("first_name")
lastName String @unique @map("last_name")

@@map("my_user")
}

使用這種方法,您可以隨意命名您的模型及其欄位,並使用 @map(用於欄位名稱)和 @@map(用於模型名稱)指向底層的表格和欄位。您的 Prisma Client API 現在看起來如下所示

const user = await prisma.myUser.create({
data: {
firstName: 'Alice',
lastName: 'Smith',
},
})

設定您的 Prisma Client API 頁面上了解更多關於此內容的資訊。