查詢資料庫
使用 Prisma Client 撰寫您的第一個查詢
現在您已產生 Prisma Client,您可以開始撰寫查詢,以讀取和寫入資料庫中的資料。
如果您正在建置 REST API,您可以在路由處理程序中使用 Prisma Client,根據傳入的 HTTP 請求讀取和寫入資料庫中的資料。如果您正在建置 GraphQL API,您可以在解析器中使用 Prisma Client,根據傳入的查詢和變更讀取和寫入資料庫中的資料。
然而,為了本指南的目的,您將只建立一個純 Node.js 腳本,以學習如何使用 Prisma Client 將查詢傳送到您的資料庫。一旦您了解 API 的運作方式,您就可以開始將其整合到您實際的應用程式碼中 (例如 REST 路由處理程序或 GraphQL 解析器)。
建立一個名為 index.js
的新檔案,並將以下程式碼新增至其中
const { PrismaClient } = require('@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)
})
async function main() {
const allUsers = await prisma.user.findMany()
console.log(allUsers)
}
現在使用此命令執行程式碼
node index.js
如果您使用資料庫內省步驟中的 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
關聯。
使用此命令執行程式碼
node index.js
在繼續下一節之前,您將使用 update
查詢「發布」您剛建立的 Post
記錄。如下調整 main
函數
async function main() {
const post = await prisma.post.update({
where: { id: 1 },
data: { published: true },
})
console.log(post)
}
現在使用與之前相同的命令執行程式碼
node index.js