使用 TypeScript 和 Prisma Postgres 查詢資料庫
使用 Prisma Client 編寫您的第一個查詢
現在您已經生成了 Prisma Client,您可以開始編寫查詢來讀取和寫入資料庫中的資料。為了本指南的目的,您將使用一個普通的 TypeScript 指令碼來探索 Prisma Client 的一些基本功能。
建立一個名為 queries.ts 的新檔案並新增以下程式碼
// 1
import { PrismaClient } from './generated/prisma'
import { withAccelerate } from '@prisma/extension-accelerate'
// 2
const prisma = new PrismaClient()
.$extends(withAccelerate())
// 3
async function main() {
// ... you will write your Prisma Client queries here
}
// 4
main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
// 5
await prisma.$disconnect()
process.exit(1)
})
以下是程式碼片段不同部分的快速概覽
- 匯入
PrismaClient建構函式和withAccelerate擴充套件。 - 例項化
PrismaClient並新增 Accelerate 擴充套件。 - 定義一個名為
main的async函式,用於向資料庫傳送查詢。 - 呼叫
main函式。 - 指令碼終止時關閉資料庫連線。
在 main 函式內部,新增以下查詢以從資料庫中讀取所有 User 記錄並記錄結果
async function main() {
const allUsers = await prisma.user.findMany()
console.log(allUsers)
}
現在使用此命令執行程式碼
npx tsx queries.ts
這應該會列印一個空陣列,因為資料庫中還沒有 User 記錄
[]
將資料寫入資料庫
您在上一節中使用的 findMany 查詢僅從資料庫中“讀取”資料(儘管它仍然是空的)。
在本節中,您將學習如何編寫查詢以一次性將新記錄“寫入”到 Post、User 和 Profile 表中。
調整 main 函式,刪除之前的程式碼並新增以下內容
async function main() {
await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@prisma.io',
posts: {
create: { title: 'Hello World' },
},
profile: {
create: { bio: 'I like turtles' },
},
},
})
const allUsers = await prisma.user.findMany({
include: {
posts: true,
profile: true,
},
})
console.dir(allUsers, { depth: null })
}
此程式碼使用巢狀寫入查詢建立新的 User 記錄以及新的 Post 和 Profile 記錄。
這些記錄透過您在 Prisma schema 中定義的關係欄位連線起來。
請注意,您還將 include 選項傳遞給 findMany,它告訴 Prisma Client 將 posts 和 profile 關係包含在返回的 User 物件上。
使用此命令執行程式碼
npx tsx queries.ts
輸出應類似於此
[
{
email: 'alice@prisma.io',
id: 1,
name: 'Alice',
posts: [
{
content: null,
createdAt: 2020-03-21T16:45:01.246Z,
updatedAt: 2020-03-21T16:45:01.246Z,
id: 1,
published: false,
title: 'Hello World',
authorId: 1,
}
],
profile: {
bio: 'I like turtles',
id: 1,
userId: 1,
}
}
]
另請注意,由於 Prisma Client 生成的型別,allUsers 變數是“靜態型別”的。您可以透過在編輯器中將滑鼠懸停在 allUsers 變數上來觀察其型別。它的型別應如下所示
const allUsers: ({
posts: {
id: number;
createdAt: Date;
updatedAt: Date;
title: string;
content: string | null;
published: boolean;
authorId: number;
}[];
profile: {
id: number;
bio: string | null;
userId: number;
} | null;
} & {
...;
})[]
展開以檢視已建立記錄的視覺檢視
查詢向 User、Post 和 Profile 表添加了新記錄
User
| id | name | |
|---|---|---|
1 | "alice@prisma.io" | "Alice" |
Post
| id | createdAt | updatedAt | title | content | published | authorId |
|---|---|---|---|---|---|---|
1 | 2020-03-21T16:45:01.246Z | 2020-03-21T16:45:01.246Z | "Hello World" | null | false | 1 |
Profile
| id | bio | userId |
|---|---|---|
1 | "I like turtles" | 1 |
Post 表中的 authorId 列和 Profile 表中的 userId 列中的數字都引用了 User 表的 id 列,這意味著 id 值 1 列因此指的是資料庫中第一條(也是唯一一條)User 記錄。
在繼續下一節之前,您將使用 update 查詢“釋出”您剛剛建立的 Post 記錄。如下調整 main 函式
async function main() {
const post = await prisma.post.update({
where: { id: 1 },
data: { published: true },
})
console.log(post)
}
現在使用與之前相同的命令執行程式碼
npx tsx queries.ts
您將看到以下輸出
{
id: 1,
title: 'Hello World',
content: null,
published: true,
authorId: 1
}
ID 為 1 的 Post 記錄現在已在資料庫中更新
Post
| id | title | content | published | authorId |
|---|---|---|---|---|
1 | "Hello World" | null | true | 1 |
恭喜!您現在已經學會了如何在應用程式中使用 Prisma Client 查詢 Prisma Postgres 資料庫。如果您在此過程中迷失方向,想了解更多查詢或探索 Prisma Accelerate 的快取功能,請檢視全面的 Prisma 入門模板。