查詢資料庫
使用 Prisma Client 撰寫您的第一個查詢
現在您已經產生了 Prisma Client,您可以開始撰寫查詢來讀取和寫入資料庫中的資料。
如果您正在建置 REST API,您可以在路由處理程序中使用 Prisma Client,根據傳入的 HTTP 請求來讀取和寫入資料庫中的資料。如果您正在建置 GraphQL API,您可以在解析器中使用 Prisma Client,根據傳入的查詢和變更來讀取和寫入資料庫中的資料。
然而,為了本指南的目的,您將僅建立一個純 Node.js 腳本,以學習如何使用 Prisma Client 將查詢傳送到您的資料庫。一旦您了解 API 的運作方式,您就可以開始將其整合到您的實際應用程式碼中(例如 REST 路由處理程序或 GraphQL 解析器)。
建立一個名為 index.ts
的新檔案,並將以下程式碼新增至其中
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function main() {
// ... you will write your Prisma Client queries here
}
main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})
以下是程式碼片段不同部分的快速概觀
- 從
@prisma/client
node 模組匯入PrismaClient
建構子 - 實例化
PrismaClient
- 定義一個名為
main
的async
函數,以將查詢傳送到資料庫 - 呼叫
main
函數 - 在腳本終止時關閉資料庫連線
根據您的模型外觀,Prisma Client API 也會有所不同。例如,如果您有一個 User
模型,您的 PrismaClient
實例會公開一個名為 user
的屬性,您可以在其上呼叫 CRUD 方法,例如 findMany
、create
或 update
。該屬性以模型命名,但第一個字母是小寫(因此對於 Post
模型,它稱為 post
,對於 Profile
,它稱為 profile
)。
以下範例均基於 Prisma 結構描述中的模型。
在 main
函數內部,新增以下查詢以從資料庫讀取所有 User
記錄並列印結果
async function main() {
const allUsers = await prisma.user.findMany()
console.log(allUsers)
}
現在使用您目前的 TypeScript 設定執行程式碼。如果您使用 tsx
,您可以像這樣執行它
npx tsx index.ts
如果您使用資料庫內省步驟中的結構描述建立資料庫,則查詢應列印一個空陣列,因為資料庫中尚無 User
記錄。
[]
如果您內省了一個具有記錄的現有資料庫,則查詢應傳回 JavaScript 物件的陣列。
將資料寫入資料庫
您在上一節中使用的 findMany
查詢僅從資料庫讀取資料。在本節中,您將學習如何撰寫查詢,以將新記錄寫入到 Post
和 User
資料表中。
調整 main
函數以將 create
查詢傳送到資料庫
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
記錄。User
記錄透過 Post.author
↔ User.posts
和 Profile.user
↔ User.profile
關聯欄位分別連接到另外兩個記錄。
請注意,您正在將 include
選項傳遞給 findMany
,這會告知 Prisma Client 在傳回的 User
物件上包含 posts
和 profile
關聯。
使用您目前的 TypeScript 設定執行程式碼。如果您使用 tsx
,您可以像這樣執行它
npx tsx index.ts
在繼續下一節之前,您將使用 update
查詢「發布」您剛剛建立的 Post
記錄。如下調整 main
函數
async function main() {
const post = await prisma.post.update({
where: { id: 1 },
data: { published: true },
})
console.log(post)
}
使用您目前的 TypeScript 設定執行程式碼。如果您使用 tsx
,您可以像這樣執行它
npx tsx index.ts