如何在 SolidStart 中使用 Prisma ORM
介绍
¥Introduction
Prisma ORM 通过类型安全的查询和流畅的开发者体验简化了数据库访问。SolidStart 是一个使用 SolidJS 构建响应式 Web 应用的现代框架,它与 Prisma 和 Postgres 完美搭配,可创建简洁且可扩展的全栈架构。
¥Prisma ORM streamlines database access with type-safe queries and a smooth developer experience. SolidStart, a modern framework for building reactive web apps with SolidJS, pairs well with Prisma and Postgres to create a clean and scalable full-stack architecture.
在本指南中,你将学习如何从头开始在 SolidStart 项目中将 Prisma ORM 与 Prisma Postgres 数据库集成。你可以在 GitHub 上找到本指南的完整示例。
¥In this guide, you'll learn how to integrate Prisma ORM with a Prisma Postgres database in a SolidStart project from scratch. You can find a complete example of this guide on GitHub.
先决条件
¥Prerequisites
1. 设置你的项目
¥ Set up your project
首先创建一个新的 SolidStart 应用。在终端运行:
¥Begin by creating a new SolidStart app. In your terminal, run:
npm init solid@latest
出现提示时,请使用以下选项:
¥Use the following options when prompted:
-
项目名称:
my-solid-prisma-app¥Project name:
my-solid-prisma-app -
这是 SolidStart 项目吗?
Yes¥Is this a SolidStart project:
Yes -
模板:
bare¥Template:
bare -
使用 TypeScript:
Yes¥Use TypeScript:
Yes
接下来,导航到你的新项目,安装依赖,并启动开发服务器:
¥Next, navigate into your new project, install dependencies, and start the development server:
cd my-solid-prisma-app
npm install
npm run dev
开发服务器运行后,请在浏览器中打开 http://localhost:3000。你应该看到 SolidStart 欢迎屏幕。
¥Once the dev server is running, open http://localhost:3000 in your browser. You should see the SolidStart welcome screen.
通过编辑 app.tsx 文件并将其内容替换为以下代码来清理默认 UI:
¥Clean up the default UI by editing the app.tsx file and replacing its content with the following code:
import "./app.css";
export default function App() {
return (
<main>
<h1>SolidStart + Prisma</h1>
</main>
);
}
2. 安装和配置 Prisma
¥ Install and Configure Prisma
2.1.安装依赖
¥2.1. Install dependencies
要开始使用 Prisma,你需要安装一些依赖:
¥To get started with Prisma, you'll need to install a few dependencies:
- Prisma Postgres (recommended)
- Other databases
npm install prisma tsx --save-dev
npm install @prisma/extension-accelerate @prisma/client dotenv
npm install prisma tsx --save-dev
npm install @prisma/client dotenv
安装完成后,请在你的项目中初始化 Prisma:
¥Once installed, initialize Prisma in your project:
npx prisma init --db --output ../src/generated/prisma
在设置 Prisma Postgres 数据库时,你需要回答几个问题。选择离你最近的区域,并为数据库选择一个容易记住的名称,例如 "我的 SolidStart 项目"
¥You'll need to answer a few questions while setting up your Prisma Postgres database. Select the region closest to your location and a memorable name for your database like "My SolidStart Project"
这将造成:
¥This will create:
-
一个包含
schema.prisma文件的prisma目录。¥A
prismadirectory with aschema.prismafile. -
A
prisma.config.tsfile for configuring Prisma -
一个 Prisma Postgres 数据库。
¥A Prisma Postgres database.
-
一个位于项目根目录、包含
DATABASE_URL文件的.env文件。¥A
.envfile containing theDATABASE_URLat the project root. -
用于生成的 Prisma 客户端的
output目录,用作src/generated/prisma。¥An
outputdirectory for the generated Prisma Client assrc/generated/prisma.
2.2.定义 Prisma Schema
¥2.2. Define your Prisma Schema
在 prisma/schema.prisma 文件中,添加以下模型,并将生成器更改为使用 prisma-client 提供程序:
¥In the prisma/schema.prisma file, add the following models and change the generator to use the prisma-client provider:
generator client {
provider = "prisma-client"
output = "../src/generated/prisma"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
authorId Int
author User @relation(fields: [authorId], references: [id])
}
这将创建两个模型:User 和 Post,它们之间存在一对多关系。
¥This creates two models: User and Post, with a one-to-many relationship between them.
2.3 Add dotenv to prisma.config.ts
To get access to the variables in the .env file, they can either be loaded by your runtime, or by using dotenv.Include an import for dotenv at the top of the prisma.config.ts
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config';
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
engine: 'classic',
datasource: {
url: env('DATABASE_URL'),
},
});
2.4.配置 Prisma 客户端生成器
¥2.4. Configure the Prisma Client generator
现在,运行以下命令创建数据库表并生成 Prisma 客户端:
¥Now, run the following command to create the database tables and generate the Prisma Client:
npx prisma migrate dev --name init
2.5.种子数据库
¥2.5. Seed the database
让我们添加一些种子数据,以便用示例用户和帖子填充数据库。
¥Let's add some seed data to populate the database with sample users and posts.
在 prisma/ 目录中创建一个名为 seed.ts 的新文件:
¥Create a new file called seed.ts in the prisma/ directory:
import { PrismaClient, Prisma } from "../src/generated/prisma/client.js";
const prisma = new PrismaClient();
const userData: Prisma.UserCreateInput[] = [
{
name: "Alice",
email: "alice@prisma.io",
posts: {
create: [
{
title: "Join the Prisma Discord",
content: "https://pris.ly/discord",
published: true,
},
{
title: "Prisma on YouTube",
content: "https://pris.ly/youtube",
},
],
},
},
{
name: "Bob",
email: "bob@prisma.io",
posts: {
create: [
{
title: "Follow Prisma on Twitter",
content: "https://www.twitter.com/prisma",
published: true,
},
],
},
},
];
export async function main() {
for (const u of userData) {
await prisma.user.create({ data: u });
}
}
main();
现在,通过更新 prisma.config.ts 来告诉 Prisma 如何运行此脚本:
¥Now, tell Prisma how to run this script by updating your prisma.config.ts:
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config';
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
seed: `tsx prisma/seed.ts`,
},
engine: 'classic',
datasource: {
url: env('DATABASE_URL'),
},
});
运行种子脚本:
¥Run the seed script:
npx prisma db seed
打开 Prisma Studio 检查你的数据:
¥And open Prisma Studio to inspect your data:
npx prisma studio
3. 将 Prisma 集成到 SolidStart
¥ Integrate Prisma into SolidStart
3.1.创建 Prisma 客户端
¥3.1. Create a Prisma Client
在项目根目录下,创建一个新的 lib 文件夹,并在其中添加一个 prisma.ts 文件:
¥At the root of your project, create a new lib folder and a prisma.ts file inside it:
mkdir -p lib && touch lib/prisma.ts
添加以下代码以创建 Prisma 客户端实例:
¥Add the following code to create a Prisma Client instance:
- Prisma Postgres (recommended)
- Other databases
import { PrismaClient } from "../src/generated/prisma/client.js";
import { withAccelerate } from "@prisma/extension-accelerate";
const prisma = new PrismaClient().$extends(withAccelerate());
export default prisma;
import { PrismaClient } from "../src/generated/prisma/client.js";
const prisma = new PrismaClient();
export default prisma;
我们建议使用连接池(例如 Prisma 加速)来高效管理数据库连接。
¥We recommend using a connection pooler (like Prisma Accelerate) to manage database connections efficiently.
如果你选择不使用 PrismaClient,请避免在长期存在的环境中全局实例化 PrismaClient。请改为按请求创建并释放客户端,以防止耗尽数据库连接。
¥If you choose not to use one, avoid instantiating PrismaClient globally in long-lived environments. Instead, create and dispose of the client per request to prevent exhausting your database connections.
3.2.创建 API 路由
¥3.2. Create an API Route
现在,让我们使用 API 路由从数据库获取数据。
¥Now, let's fetch data from the database using an API route.
在 src/routes/api/users.ts 目录下创建一个新文件:
¥Create a new file at src/routes/api/users.ts:
import prisma from "../../../lib/prisma";
export async function GET() {
const users = await prisma.user.findMany({
include: {
posts: true,
},
});
return new Response(JSON.stringify(users), {
headers: { "Content-Type": "application/json" },
});
}
3.3.在你的组件中获取数据
¥3.3. Fetch Data in Your Component
在你的 app.tsx 文件中,使用 createResource 从新的 API 路由获取数据:
¥In your app.tsx file, use createResource to fetch data from your new API route:
import "./app.css";
import { createResource } from "solid-js";
import { User, Post } from "./generated/prisma/client";
type UserWithPosts = User & {
posts: Post[];
};
const fetchUsers = async () => {
const res = await fetch("http://localhost:3000/api/users");
return res.json();
};
export default function App() {
const [users, { mutate, refetch }] = createResource<UserWithPosts[]>(fetchUsers);
return (
<main>
<h1>SolidStart + Prisma</h1>
</main>
);
}
createResource 是一个用于管理异步数据的 SolidJS 钩子。它自动跟踪加载和错误状态。了解更多。
¥createResource is a SolidJS hook for managing async data. It tracks loading and error states automatically. Learn more.
3.4.显示数据
¥3.4. Display the Data
要显示用户及其帖子,请使用 SolidJS 的 <For> 组件:
¥To show the users and their posts, use SolidJS's <For> component:
import "./app.css";
import { createResource, For } from "solid-js";
import { User, Post } from "./generated/prisma/client";
type UserWithPosts = User & {
posts: Post[];
};
const fetchUsers = async () => {
const res = await fetch("http://localhost:3000/api/users");
return res.json();
};
export default function App() {
const [users, { mutate, refetch }] =
createResource<UserWithPosts[]>(fetchUsers);
return (
<main>
<h1>SolidJS + Prisma</h1>
<For each={users() ?? []}>
{(user) => (
<div>
<h3>{user.name}</h3>
<For each={user.posts}>{(post) => <p>{post.title}</p>}</For>
</div>
)}
</For>
</main>
);
}
<For> 会以响应式方式循环遍历数组。可以将其想象成 React 中的 .map()。了解更多
¥<For> loops through an array reactively. Think of it like .map() in React. Learn more
3.5.添加加载和错误状态
¥3.5. Add Loading and Error States
使用 SolidJS 的 <Show> 组件处理加载和错误情况:
¥Use SolidJS's <Show> component to handle loading and error conditions:
import "./app.css";
import { createResource, For, Show } from "solid-js";
import { User, Post } from "./generated/prisma/client";
type UserWithPosts = User & {
posts: Post[];
};
const fetchUsers = async () => {
const res = await fetch("http://localhost:3000/api/users");
return res.json();
};
export default function App() {
const [users, { mutate, refetch }] =
createResource<UserWithPosts[]>(fetchUsers);
return (
<main>
<h1>SolidJS + Prisma</h1>
<Show when={!users.loading} fallback={<p>Loading...</p>}>
<Show when={!users.error} fallback={<p>Error loading data</p>}>
<For each={users()}>
{(user) => (
<div>
<h3>{user.name}</h3>
<For each={user.posts}>{(post) => <p>{post.title}</p>}</For>
</div>
)}
</For>
</Show>
</Show>
</main>
);
}
<Show> 有条件地渲染内容。它类似于 if 语句。了解更多
¥<Show> conditionally renders content. It's similar to an if statement. Learn more
你已完成!你刚刚创建了一个连接到 Prisma Postgres 数据库的 SolidStart 应用。
¥You're done! You've just created a SolidStart app connected to a Prisma Postgres database.
后续步骤
¥Next Steps
现在你已经拥有一个连接到 Prisma Postgres 数据库的 SolidStart 应用,你可以:
¥Now that you have a working SolidStart app connected to a Prisma Postgres database, you can:
-
使用更多模型和关系扩展你的 Prisma 模式
¥Extend your Prisma schema with more models and relationships
-
添加创建/更新/删除路由和表单
¥Add create/update/delete routes and forms
-
探索身份验证、验证和乐观更新
¥Explore authentication, validation, and optimistic updates
-
使用 Prisma Postgres 启用查询缓存以获得更好的性能
¥Enable query caching with Prisma Postgres for better performance
更多信息
¥More Info
Stay connected with Prisma
Continue your Prisma journey by connecting with our active community. Stay informed, get involved, and collaborate with other developers:
- Follow us on X for announcements, live events and useful tips.
- Join our Discord to ask questions, talk to the community, and get active support through conversations.
- Subscribe on YouTube for tutorials, demos, and streams.
- Engage on GitHub by starring the repository, reporting issues, or contributing to an issue.