跳到主要內容

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

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

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

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

然而,為了本指南的目的,你將只建立一個普通的 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

如果你使用資料庫內省步驟中的 schema 建立了一個數據庫,查詢應該會列印一個空陣列,因為資料庫中還沒有 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.