使用 JavaScript 和 PlanetScale 查詢資料庫
使用 Prisma Client 編寫你的第一個查詢
現在你已經生成了 Prisma Client,你可以開始編寫查詢來從資料庫中讀取和寫入資料。為了本指南的目的,你將使用一個簡單的 Node.js 指令碼來探索 Prisma Client 的一些基本功能。
建立一個名為 index.js 的新檔案,並將以下程式碼新增到其中
const { PrismaClient } = require('./generated/prisma')
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模組匯入PrismaClient建構函式 - 例項化
PrismaClient - 定義一個名為
main的async函式,用於向資料庫傳送查詢 - 呼叫
main函式 - 指令碼終止時關閉資料庫連線
在 main 函式內部,新增以下查詢以讀取資料庫中的所有 User 記錄並列印結果
async function main() {
// ... you will write your Prisma Client queries here
const allUsers = await prisma.user.findMany()
console.log(allUsers)
}
現在使用此命令執行程式碼
node index.js
這應該會列印一個空陣列,因為資料庫中還沒有任何 User 記錄
[]
將資料寫入資料庫
你在上一節使用的 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
輸出應類似於以下內容
[
{
email: 'alice@prisma.io',
id: 1,
name: 'Alice',
posts: [
{
content: null,
createdAt: 2020-03-21T16:45:01.246Z,
updatedAt: 2020-03-21T16:45:01.246Z,
id: 1,
published: false,
title: 'Hello World',
authorId: 1,
}
],
profile: {
bio: 'I like turtles',
id: 1,
userId: 1,
}
}
]
此查詢向 User 和 Post 表添加了新記錄
使用者
| id | name | |
|---|---|---|
1 | "alice@prisma.io" | "Alice" |
Post
| id | createdAt | updatedAt | title | content | published | authorId |
|---|---|---|---|---|---|---|
1 | 2020-03-21T16:45:01.246Z | 2020-03-21T16:45:01.246Z | "Hello World" | null | false | 1 |
Profile
| id | bio | userId |
|---|---|---|
1 | "I like turtles" | 1 |
注意:
Post表中authorId列和Profile表中userId列中的數字都引用了User表的id列,這意味著id值1列因此引用資料庫中的第一條(也是唯一一條)User記錄。
在繼續下一節之前,你將使用一個 update 查詢“釋出”你剛剛建立的 Post 記錄。調整 main 函式如下
async function main() {
const post = await prisma.post.update({
where: { id: 1 },
data: { published: true },
})
console.log(post)
}
現在使用與之前相同的命令執行程式碼
node index.js
你將看到以下輸出
{
id: 1,
title: 'Hello World',
content: null,
published: true,
authorId: 1
}
Post 記錄,其 id 為 1,現在已在資料庫中更新
Post
| id | title | content | published | authorId |
|---|---|---|---|---|
1 | "Hello World" | null | true | 1 |
太棒了,你剛剛首次使用 Prisma Client 將新資料寫入了你的資料庫 🚀