一、Prisma Client API入门
参考:Prisma Client API reference
1.1 初始化项目
检查node版本:
➜ prisma-js-study node -v
v18.17.0
创建项目
mkdir prisma-js-study
cd prisma-js-study
npm init -y
# 开发环境依赖CLI
npm install prisma --save-dev
# 生产环境
npm install @prisma/client --save
package.json
{
"name": "prisma-js-study",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "node ./script.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"prisma": "^5.11.0"
},
"dependencies": {
"@prisma/client": "^5.11.0"
}
}
script.js
const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();
async function main() {
console.log("Hello Node");
}
main()
.catch((e) => {
throw e;
})
.finally(async () => {
if (prisma) {
await prisma.$disconnect();
}
});
1.2 初始化prisma
创建prisma/schema.prisma
文件:
datasource db {
provider = "sqlite"
url = "file:./dev.db"
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
name String?
email String @unique
}
初始化prisma数据库:
# 生成模型
prisma generate
# 执行第一次数据库变更
npx prisma migrate dev --name init
使用prisma自带工具,创建初始数据:
npx prisma studio
1.3 prisma查询
修改script.js
const { PrismaClient } = require("@prisma/client");
# 记录日志级别
const prisma = new PrismaClient({ log: ["query", "info"] });
async function main() {
const result = await prisma.user.findMany();
console.log(result);
}
main()
.catch((e) => {
throw e;
})
.finally(async () => {
if (prisma) {
await prisma.$disconnect();
}
});
查询所有用户:
// 查询所有用户
async function getAllUser(){
return await prisma.user.findMany();
}
创建新用户:
// 创建新用户
async function createUser() {
return await prisma.user.create({
data: {
email: "test2@123.com",
name: "test2",
},
});
}
根据id查询单个用户:
// 根据id查询单个用户
async function findOneUser(){
return await prisma.user.findUnique({
where:{
email:"test2@123.com"
}
})
}
查询部分列数据
// 查询部分列数据
async function getUserNames(){
return await prisma.user.findMany({
select:{
id:true,
name:true
}
})
}
更新的用户信息:
async function updateUser(){
return await prisma.user.update({
where:{
email:"test2@123.com"
},
data:{
name:"test2-update"
}
})
}
增加Post表,修改schema.prisma
:
model User {
id Int @id @default(autoincrement())
name String?
email String @unique
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?
}
执行数据库变更记录
npx prisma migrate dev --name add-post
创建一篇文章:
// 新建一篇文章
async function createPost(){
return await prisma.post.create({
data:{
tittle:"Hello world",
content:"My First Post"
}
})
}
# 终端执行结果
➜ prisma-js-study npm run dev
> prisma-js-study@1.0.0 dev
> node ./script.js
{
id: 1,
tittle: 'Hello world',
content: 'My First Post',
published: false,
authorId: null
}
将用户和文章关联起来:
// 用户和文章关联起来
async function joinUserAndPost(){
return await prisma.post.update({
where:{
id:1
},
data:{
author:{
connect:{email:"test2@123.com"}
}
}
})
}
嵌套查询,查询用户和文章:
// 查询用户和文章
async function getUserAndPost(){
return await prisma.user.findUnique({
where: { email: "test2@123.com" },
include: { posts:true },
});
}
新建用户和文章:
// 新建用户和文章
async function createUserAndPost(){
return await prisma.user.create({
data:{
name:"jiasen1",
email:"jiasen1@123.com",
posts:{
create:{
title:"A NextJs Post",
content:"Second Post"
}
}
}
})
}
模糊查询:
// 模糊查询
async function findUserByName() {
return await prisma.user.findMany({
where: {
name: {
// 过滤查询名字以“t”开头的用户
startsWith: "t",
// 包含
contains: "test"
},
},
});
}
分页查询:
// 模拟分页
async function pageUser() {
return await prisma.user.findMany({
// skip: 0,
skip: 2,
take: 2,
});
}
更新或插入:
// 更新插入
async function saveOrUpdate() {
return await prisma.user.upsert({
where: {
email: "jiasen123@123.com",
},
update: {
name: "jiasen123",
},
create: {
name: "jiasen123",
email: "jiasen123@123.com",
},
});
}
删除关联用户的帖子:
// 删除关联用户的帖子
async function deleteNested() {
return await prisma.user.update({
where: {
email: "jiasen1@123.com",
},
data: {
posts: {
deleteMany: {},
},
},
});
}
...