跳到主要内容

全栈

全栈框架,如 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 应用
© . All rights reserved.