跳到主要內容

全栈

全栈框架,例如 Next.js、Remix 或 SvelteKit,模糊了服务器和客户端之间的界限。 这些框架还为在服务器上获取和更改数据提供了不同的模式。

你可以使用 Prisma Client,从你选择的框架中,从应用程序的服务器端部分查询你的数据库。

支援的框架

這裡列出一些你可以與 Prisma ORM 一起使用的框架和函式庫(非詳盡列表)

全棧應用範例 (例如 Next.js)

提示

如果你想學習如何使用 Next.js 和 Prisma ORM 建構應用程式,請查看這個全面的影片教學

假設你有一個 Prisma schema,看起來像這樣

datasource db {
provider = "sqlite"
url = "file:./dev.db"
}

generator client {
provider = "prisma-client-js"
}

model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User? @relation(fields: [authorId], references: [id])
authorId Int?
}

model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}

你現在可以使用 Prisma Client API 在 getServerSideProps、getStaticProps、API 路由中,或使用 API 函式庫(例如 tRPC 和 GraphQL)來實作查詢資料庫的邏輯。

getServerSideProps

// (in /pages/index.tsx)

// Alternatively, you can use `getStaticProps`
// in place of `getServerSideProps`.
export const getServerSideProps = async () => {
const feed = await prisma.post.findMany({
where: {
published: true,
},
})
return { props: { feed } }
}

Next.js 會將 props 傳遞給你的 React 組件,你可以在其中顯示來自資料庫的資料。

API 路由

// Fetch all posts (in /pages/api/posts.ts)
const prisma = new PrismaClient()

export default async function handle(req, res) {
const posts = await prisma.post.findMany({
where: {
published: true,
},
})
res.json(posts)
}

請注意,你可以在 Next.js API 路由內部使用 Prisma ORM 來向你的資料庫發送查詢——使用 REST、GraphQL 和 tRPC。

然後你可以在你的前端擷取資料並顯示它。

即用型全棧範例專案

你可以在 prisma-examples 儲存庫中找到幾個即用型範例,展示如何使用 Prisma Client 建構全棧應用程式。prisma-examples

範例描述
Next.js全棧 Next.js 15 應用程式
Next.js (GraphQL)使用 GraphQL Yoga、Pothos 和 Apollo Client 的全棧 Next.js 應用程式
Remix使用 actions 和 loaders 的全棧 Remix 應用程式
SvelteKit使用 actions 和 loaders 的全棧 Sveltekit 應用程式
Nuxt使用 API 路由的全棧 Nuxt 應用程式