跳到主要内容

全栈

全栈框架(如 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 APIgetServerSidePropsgetStaticProps、API 路由或使用 API 库(如 tRPCGraphQL)中实现查询数据库的逻辑。

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 应用程序