跳到主要內容

全棧

全棧框架,如 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[]
}

您現在可以在 getServerSidePropsgetStaticProps、API 路由內部實現使用 Prisma Client API 查詢資料庫的邏輯,或者使用諸如 tRPCGraphQL 等 API 庫。

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 構建全棧應用程式的可執行示例。

示例描述
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 應用
© . This site is unofficial and not affiliated with Prisma Data, Inc.