快速开始
准备
nodejs 版本高于 v14.17.0
1 创建项目
# 创建文件夹
mkdir hello-prisma
cd hello-prisma
# 初始化
npm init -y
# 安装依赖
npm install typescript ts-node @types/node --save-dev
配置 typescript
touch tsconfig.json
{
"compilerOptions": {
"sourceMap": true,
"outDir": "dist",
"strict": true,
"lib": ["esnext"],
"esModuleInterop": true
}
}
安装依赖
npm install prisma --save-dev
初始化数据源
npx prisma init --datasource-provider sqlite
2 创建模型
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)
author User @relation(fields: [authorId], references: [id])
authorId Int
}
3 创建数据库
npx prisma migrate dev --name init
4 通过 Prisma Client 体验数据库操作
增加数据
// touch script.ts
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
async function main() {
// ... you will write your Prisma Client queries here
const user = await prisma.user.create({
data: {
name: "Alice",
email: "alice@prisma.io",
},
});
console.log(user);
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});
执行命令
npx ts-node script.ts
查询数据
async function main() {
const users = await prisma.user.findMany();
console.log(users);
}
关联创建
const user = await prisma.user.create({
data: {
name: "Bob",
email: "bob@prisma.io",
posts: {
create: {
title: "Hello World",
},
},
},
});
关联查询
const usersWithPosts = await prisma.user.findMany({
include: {
posts: true,
},
});
console.dir(usersWithPosts, { depth: null });
5 使用 GUI 操作数据库
npx prisma studio