跳到主要內容

JavaScript 專案中 MySQL 的內省

使用 Prisma ORM 內省您的資料庫

為了本指南的目的,我們將使用一個包含三個表的演示 SQL 模式

CREATE TABLE User (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
name VARCHAR(255),
email VARCHAR(255) UNIQUE NOT NULL
);

CREATE TABLE Post (
id INTEGER PRIMARY KEY AUTO_INCREMENT 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 User(id)
);

CREATE TABLE Profile (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
bio TEXT,
userId INTEGER UNIQUE NOT NULL,
FOREIGN KEY (userId) REFERENCES User(id)
);
展開查看錶的圖形概覽

使用者

列名型別主鍵外部索引鍵必需預設
idINTEGER✔️✔️自增
nameVARCHAR(255)-
emailVARCHAR(255)✔️-

帖子

列名型別主鍵外部索引鍵必需預設
idINTEGER✔️✔️自增
createdAtDATETIME(3)✔️now()
titleVARCHAR(255)✔️-
contentTEXT-
publishedBOOLEAN✔️false
authorIdINTEGER✔️✔️false

檔案

列名型別主鍵外部索引鍵必需預設
idINTEGER✔️✔️自增
bioTEXT-
userIdINTEGER✔️✔️-

下一步,您將內省您的資料庫。內省的結果將是您 Prisma 模式中的一個資料模型

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

npx prisma db pull

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

內省完成後,您的 Prisma 模式會更新

Introspect your database

資料模型現在看起來類似於這樣(請注意,模型的欄位已重新排序以提高可讀性)

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

@@index([authorId], map: "authorId")
}

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

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

有關模式定義的詳細資訊,請參閱Prisma 模式參考

Prisma ORM 的資料模型是您的資料庫模式的宣告性表示,並作為生成的 Prisma Client 庫的基礎。您的 Prisma Client 例項將公開為這些模型量身定製的查詢。

目前,資料模型存在一些小“問題”

  • User 關係欄位採用大寫形式,因此不符合 Prisma 的命名約定。為了表達更多的“語義”,如果此欄位名為 author 以更好地描述 UserPost 之間的關係,那也將很好。
  • User 上的 PostProfile 關係欄位以及 Profile 上的 User 關係欄位都採用大寫形式。為了遵守 Prisma 的命名約定,這兩個欄位都應該小寫為 postprofileuser
  • 即使小寫後,User 上的 post 欄位仍然有點命名不當。那是因為它實際上指的是一個帖子列表——因此,更好的名稱應該是複數形式:posts

這些更改對於生成的 Prisma Client API 很重要,因為使用小寫的 authorpostsprofileuser 關係欄位對於 JavaScript/TypeScript 開發者來說會更自然和符合習慣。因此,您可以配置您的 Prisma Client API

因為關係欄位虛擬的(即它們不會直接在資料庫中體現),您可以在 Prisma 模式中手動重新命名它們而無需觸及資料庫

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

@@index([authorId], map: "authorId")
}

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

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

在此示例中,資料庫模式確實遵循了 Prisma ORM 模型的命名約定(只有從內省生成的虛擬關係欄位不符合約定,需要調整)。這優化了生成的 Prisma Client API 的人體工程學。

不過,有時您可能希望對 Prisma Client API 中公開的列和表的名稱進行額外更改。一個常見的例子是將資料庫模式中常用的snake_case(蛇形命名法)轉換為對於 JavaScript/TypeScript 開發者而言更自然的PascalCase(帕斯卡命名法)和camelCase(駝峰命名法)。

假設您從基於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 頁面。

© . This site is unofficial and not affiliated with Prisma Data, Inc.