prisma学习使用
uwupu 啦啦啦啦啦

prisma

nodejs orm工具

依赖:prisma (-D)

Installation

  1. 安装依赖:npm install prisma -D
  2. 初始化:npx prisma init --datasource-provider sqllite
  3. 建模,文件:schema.prisma
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
}
  1. npx prisma migrate dev --name init:三个作用:创建sql文件;更新数据库内容;生成ClientAPI。/ 也可以使用npx prisma generate生成ClientAPI。
  2. 连接数据库
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main() {
// ... you will write your Prisma Client queries here
}

main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})
  1. Create/Read 插入/读取

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    // create

    //单个创建
    const user = await prisma.user.create({
    data: {
    name: 'Alice',
    email: '[email protected]',
    },
    })

    // 嵌套创建
    const user = await prisma.user.create({
    data: {
    name: 'Bob',
    email: '[email protected]',
    posts: {
    create: [
    {
    title: 'Hello World',
    published: true
    },
    {
    title: 'My second post',
    content: 'This is still a draft'
    }
    ],
    },
    },
    })
    console.log(user)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // read
    const users = await prisma.user.findMany()
    console.log(users)

    // 嵌套查询
    const usersWithPosts = await prisma.user.findMany({
    include: {
    posts: true,
    },
    })
    console.dir(usersWithPosts, { depth: null })
  2. Prisma的工具:Prisma Studio

    1
    npx prisma studio

Usage

Database

schema与数据库同步

prisma支持从schema更新数据库结构,使用migrate子参数。

prisma会生成“迁移文件记录每次数据库结构发生的变化

prisma的migrate有两种方式:

  • dev:开发环境模式。
    • 生成迁移文件并应用到数据库;
    • 可选支持seed脚本,seed脚本可以通过typescript脚本数据库添加随机数据。注:==配置该功能每次进行migrate就会清理数据库所有数据==。==不配置不会清理数据库数据==。==可以通过–skip-seed跳过==。
  • deploy:生产环境模式。
    • 不生成迁移文件,将最后一次的迁移文件应用到数据库。
    • 不会清理数据库。
1
npx prisma migrate dev/deploy [--skip-seed] [--name 迁移记录名称]

Nodejs: CRUD

CRUD,即增查改删。

Create

基础

1
2
3
4
5
6
const newUser = await prisma.user.create({
data: {
name: 'Alice',
email: '[email protected]',
},
});

扩展

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const newUser = await prisma.user.create({
data: {
name: 'Alice',
email: '[email protected]',
// 嵌套创建
posts:{
create:{
title: "Hello World"
}
},
// 关联记录(外键)
classNo:{
connect: {
id: 1
}
},
// 枚举
role: 'ADMIN',
},
});
1
2
3
4
5
6
7
//插入多条数据
const users = await prisma.user.createMany({
data: [
{ name: 'Alice', email: '[email protected]' },
{ name: 'Bob', email: '[email protected]' },
],
});

Read

基础

1
2
3
4
// 查询所有数据
await prisma.user.findMany();
// 查询单条数据
await prisma.user.findUnique();

扩展

1
2
3
4
5
6
7
8
9
10
const users = await prisma.user.findMany({
where: { /* 过滤条件 */ },
orderBy: { /* 排序条件 */ },
select: { /* 选择返回的字段 */ },
include: { /* 包含关联模型 */ },
skip: 0, // 跳过前 N 条记录
take: 10, // 返回的记录数
distinct: ['field'], // 去重字段
cursor: { id: 1 }, // 游标定位
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// where
where: {
// 简单条件
id: 1,
name: "Alice",
age: { gt: 18 }, // 大于 18
// lt 小于 lte小于等于 gte大于等于 equals等于
email: { contains: "@example.com" }, // 包含字符串
// 组合条件
AND: [{ age: { gt: 18 } }, { age: { lt: 30 } }], // 年龄大于 18 且小于 30
OR: [{ name: "Alice" }, { name: "Bob" }], // 名字是 Alice 或 Bob
NOT: { age: { lt: 18 } }, // 年龄不小于 18
// 关联模型条件
posts: { some: { title: { contains: "Prisma" } } }, // 至少有一篇标题包含 "Prisma" 的文章
}

// orderBy
orderBy: {
// 单字段排序
age: "asc", // 按年龄升序
name: "desc", // 按名字降序
// 多字段排序
[ { age: "asc" }, { name: "desc" } ], // 先按年龄升序,再按名字降序
}

// select 选择指定字段
select: {
// 选择特定字段
id: true,
name: true,
// 排除特定字段
email: false,
// 选择关联模型字段
posts: { select: { title: true } },
}

// include
include: {
// 包含关联模型
posts: true, // 包含所有文章
posts: { select: { title: true } }, // 包含文章,但只选择标题
posts: { where: { published: true } }, // 包含已发布的文章
posts: { orderBy: { createdAt: "desc" } }, // 包含文章并按创建时间降序
}

Update

1
2
3
4
5
6
7
8
9
10
11
// 单条数据更新 (这里要让where只匹配到一个数据)
const updatedUser = await prisma.user.update({
where: {
id: 1, // 条件:更新 id 为 1 的用户
},
data: {
name: 'Alice', // 新数据:将 name 更新为 'Alice'
},
});
//多条数据更新
await prisma.user.updateMany(...)

Delete

1
2
await prisma.user.delete({where: {...}});
await prisma.user.deleteMany({where:{...}});

Schema

基础

1
2
3
4
5
6
7
8
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
password String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

扩展

1
2
3
4
5
6
7
8
9
10
11
model User {
id Int @id @default(autoincrement()) # @id 主键; @default默认值; @default(autoincrement()) 自增
email String @unique # @unique 唯一
name String? # "?"可选参数
info3 String @map('info_3') # 指定特定数据库列名
info4 String @ignore # 只创建在模型,不会出现在数据库
createdAt DateTime @default(now())
@@index([name]) # 在name上创建索引
@@index([name,email]) #复合索引
@@map("user_1") # 指定数据库表名
}
  • 参数类型:Int, String, Boolean, DateTime, Float, Json, Bytes

  • 定义字段在数据库的字段类型: @db.TYPE。比如:@db.Int

    • Int, VarChar(255), Text, Boolean, Timestamp, Decimal(precision, scale)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# 一对多
model User {
id Int @id @default(autoincrement())
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
userId Int
user User @relation(fields: [userId], references: [id])
}


# 多对多
model User {
id Int @id @default(autoincrement())
roles Role[]
}
model Role {
id Int @id @default(autoincrement())
users User[]
}

# 一对一
model User {
id Int @id @default(autoincrement())
profile Profile?
}

model Profile {
id Int @id @default(autoincrement())
userId Int @unique
user User @relation(fields: [userId], references: [id])
}


OTHER

从数据库生成schema

1
npx prisma db pull

新特性:通过schema分离

被删除的部分

1
2
3
4
password  String   @notNull 				# 验证:非空
info String @length(min:5,max:100) # 验证:长度不得低于5高于100
age Int @min(0) @max(1000) # 验证:值范围需在0-1000之间
info2 String @regex("正则表达式") # 验证:正则表达式

被误导了,没有这一部分。

 评论