使用 TypeScript 和 Prisma ORM 查詢現有 MySQL 資料庫
使用 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/clientNode 模組匯入PrismaClient建構函式 - 例項化
PrismaClient - 定義一個名為
main的async函式,用於向資料庫傳送查詢 - 呼叫
main函式 - 指令碼終止時關閉資料庫連線
根據你的模型,Prisma Client API 也會有所不同。例如,如果你有一個 User 模型,你的 PrismaClient 例項會公開一個名為 user 的屬性,你可以在其上呼叫 CRUD 方法,例如 findMany、create 或 update。該屬性以模型命名,但首字母小寫(因此對於 Post 模型,它被稱為 post;對於 Profile 模型,它被稱為 profile)。
以下示例均基於 Prisma schema 中的模型。
在 main 函式內部,新增以下查詢以從資料庫讀取所有 User 記錄並列印結果
async function main() {
const allUsers = await prisma.user.findMany()
console.log(allUsers)
}
現在,使用你當前的 TypeScript 設定執行程式碼。如果你正在使用 tsx,可以這樣執行它
npx tsx index.ts
如果你使用資料庫內省步驟中的 schema 建立了資料庫,查詢應該會列印一個空陣列,因為資料庫中還沒有 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