跳到主要內容

使用 JavaScript 和 Prisma ORM 查詢現有 MySQL 資料庫

使用 Prisma Client 編寫您的第一個查詢

現在您已經生成了 Prisma Client,您可以開始編寫查詢來讀寫資料庫中的資料。

如果您正在構建 REST API,您可以在路由處理程式中使用 Prisma Client,根據傳入的 HTTP 請求讀寫資料庫中的資料。如果您正在構建 GraphQL API,您可以在解析器中使用 Prisma Client,根據傳入的查詢和變更來讀寫資料庫中的資料。

然而,為了本指南的目的,您將只建立一個簡單的 Node.js 指令碼,學習如何使用 Prisma Client 向資料庫傳送查詢。一旦您瞭解了 API 的工作原理,您就可以開始將其整合到您的實際應用程式程式碼中(例如 REST 路由處理程式或 GraphQL 解析器)。

建立一個名為 index.js 的新檔案,並新增以下程式碼

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)
})
index.js
async function main() {
const allUsers = await prisma.user.findMany()
console.log(allUsers)
}

現在使用此命令執行程式碼

node index.js

如果您使用資料庫自省步驟中的模式建立了資料庫,該查詢應列印一個空陣列,因為資料庫中還沒有 User 記錄。

[]

如果您自省了一個包含記錄的現有資料庫,該查詢應返回一個 JavaScript 物件陣列。

將資料寫入資料庫

您在上一節中使用的 findMany 查詢僅 讀取 資料庫中的資料。在本節中,您將學習如何編寫查詢以將新記錄 寫入 PostUser 表中。

調整 main 函式以向資料庫傳送 create 查詢

index.js
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 記錄以及新的 PostProfile 記錄。User 記錄透過 Post.authorUser.postsProfile.userUser.profile 關係欄位分別連線到其他兩條記錄。

請注意,您正在將include 選項傳遞給 findMany,這告訴 Prisma Client 在返回的 User 物件中包含 postsprofile 關係。

使用此命令執行程式碼

node index.js

在進入下一節之前,您將使用 update 查詢“釋出”您剛剛建立的 Post 記錄。按如下方式調整 main 函式

index.js
async function main() {
const post = await prisma.post.update({
where: { id: 1 },
data: { published: true },
})
console.log(post)
}

現在使用與之前相同的命令執行程式碼

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