[TOC]
什么是Prisma?
Next-generation ORM for Node.js and TypeScript(下一代Node.js的ORM框架),目前仅支持
PostgreSQL
,MySQL
andSQLite
.
一步一步创建
-
创建项目目录
$ mkdir hello-prisma && cd hello-prisma
-
初始化项目并安装依赖文件
$ npm init -y
$ npm install prisma typescript ts-node @types/node --save-dev
-
创建
tsconfig.json
, 并输入以下内容-
{ "compilerOptions": { "sourceMap": true, "outDir": "dist", "strict": true, "lib": ["esnext"], "esModuleInterop": true } }
-
-
创建
Prisma schema
文件npx prisma init
- 生成了如下文件
-
设置数据库,修改
prisma/schema.prisma
的provider
属性-
datasource db { // provider可以设置三种属性: mysql, sqlite, postgresql provider = "mysql" url = env("DATABASE_URL") } generator client { provider = "prisma-client-js" }
-
-
修改
env
文件中的DATABASE_URL
,生成规则:数据库名称://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA
,例如我的mysql
地址为:mysql://root:12345678@localhost:3432/mydb?schema=public
-
向
prisma/schema.prisma
中追加内容-
model Post { id Int @default(autoincrement()) @id createdAt DateTime @default(now()) updatedAt DateTime @updatedAt title String @db.VarChar(255) content String? published Boolean @default(false) author User @relation(fields: [authorId], references: [id]) authorId Int } model Profile { id Int @default(autoincrement()) @id bio String? user User @relation(fields: [userId], references: [id]) userId Int @unique } model User { id Int @default(autoincrement()) @id email String @unique name String? posts Post[] profile Profile? }
-
-
生成数据库表
$ npx prisma migrate dev --name init
生成了如下文件:
- 安装
Prisma Client
:$ npm install @prisma/client
- 创建
index.ts
并输入输入下内容
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function main() {
// ... you will write your Prisma Client queries here
const allUsers = await prisma.user.findMany()
console.log(allUsers)
}
main()
.catch((e) => {
throw e
})
.finally(async () => {
await prisma.$disconnect()
})
通过npx ts-node index.ts
执行上面的代码,输出的结果为:[]
- 更新man方法
async function main() {
// ... you will write your Prisma Client queries here
await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@prisma.io',
posts: {
create: { title: 'Hello World' },
},
profile: {
create: { bio: 'I like turtles' },
},
},
})
const allUsers = await prisma.user.findMany({
include: {
posts: true,
profile: true,
},
})
console.dir(allUsers, { depth: null })
}
执行代码结果为
[
{
email: 'alice@prisma.io',
id: 1,
name: 'Alice',
posts: [
{
content: null,
createdAt: 2020-03-21T16:45:01.246Z,
id: 1,
published: false,
title: 'Hello World',
authorId: 1,
}
],
profile: {
bio: 'I like turtles',
id: 1,
userId: 1,
}
}
]
- 在
Prisma Studio
中查看数据:$ npx prisma studio
选择一项看到下面的数据