Upsert 操作
Upsert 操作允许您在记录存在时更新它,或者在记录不存在时创建它。
upsert
接受三个参数
- 一个唯一的过滤器
- 一个创建参数的元组
- 一个更新数据的列表
此示例使用以下 Prisma 模式
model Post {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
published Boolean
title String
content String?
views Int @default(0)
}
以下示例搜索帖子,如果找到则更新它,否则创建它。
use prisma::post;
let post: post::Data = client
.post()
.upsert(
// Unique filter
post::id::equals("upsert".to_string()),
// 'create' helper function for constructing a create argument tuple
post::create(
true,
"title".to_string(),
"upsert".to_string(),
vec![]
),
// Vec of updates to apply if record already exists
vec![
post::content::set(Some("new content".to_string())),
post::views::increment(1)
]
)
.exec()
.await
.unwrap();