创建查询
create
和 create_many
允许您轻松创建一条或多条记录。
模型的必填字段需要作为 create
的参数或 `create_many` 的元组中的单个参数提供,而可选字段可以在所有必填字段之后以 Vec 的形式提供。
提供可选字段的值时,需要将值包装在“字段标识符”中,以便客户端知道要设置哪个字段。这些通常看起来像 model::field::set
。对于必填字段,不需要这样做,因为它们在参数列表中拥有自己的位置。
嵌套创建尚不受支持。
示例使用以下模式
generator client {
provider = "cargo prisma"
output = "src/prisma.rs"
}
model Post {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
published Boolean
title String
content String?
desc String?
comments Comment[]
}
model Comment {
id String @id @default(cuid())
createdAt DateTime @default(now())
content String
post Post @relation(fields: [postID], references: [id])
postID String
}
创建
以下示例创建了一个帖子并覆盖了其自动生成的 id
字段。
use prisma::post;
let post: post::Data = client
.post()
.create(
// Required fields are individual arguments.
// Wrapping their values is not necessary.
true,
"what up".to_string(),
// All other fields can be passed in the last argument
vec![
// Generated fields can be overwritten like regular fields
post::id::set("id".to_string()),
// Non-required fields require being wrapped in an Option
post::content::set(Some("content".to_string()))
]
)
.exec()
.await?;
连接关系
关系字段模块的 connect
函数可用于将新记录与现有记录连接起来。它接受单个唯一过滤器作为参数。
以下示例创建了一个新的评论并将其链接到一个帖子。
use prisma::{comment, post};
let comment: comment::Data = client
.comment()
.create(
"content".to_string(),
// If post wasn't required, then this would need
// to be wrapped in comment::post::connect(..).
post::id::equals("id".to_string())
vec![]
)
.exec()
.await?;
这种连接记录的方式等同于直接设置关系的外键值,例如,使用 comment::post_id::set()
设置上面示例中的 post_id
。
创建(未经检查)
自 v0.6.7 起可用
create_unchecked
类似于 create
,但仅允许使用 UncheckedSetParam
设置标量字段。unchecked
是 Prisma 中的一个术语,用于描述仅接受模型标量字段的输入。
use prisma::{comment, post};
let comment: comment::Data = client
.comment()
.create_unchecked(
"content".to_string(),
// requires providing value for postID foreign key,
// rather than connecting a relation
0,
vec![]
)
.exec()
.await?;
创建多个
create_many
可用于创建单个模型类型的多条记录。它接受一个 Vec
,其中包含与 create_unchecked
相同形状的元组,因此只能设置标量字段。
SQLite 对 create_many
的支持 **不稳定**,但可以通过在 prisma-client-rust
和 prisma-client-rust-cli
中添加 sqlite-create-many
功能来启用,在您的 Cargo.toml
文件中。
为了帮助构建正确形状的元组,每个模型模块都包含一个 create_unchecked
函数,该函数接受模型的标量字段并返回正确的元组。
以下示例迭代标题数组,将其转换为元组并创建多个帖子。
use prisma::post;
let titles = [
"Title 1",
"Title 2",
"Title 3"
]
let posts: i64 = client
.post()
.create_many(
titles
.iter()
.map(|title| post::create_unchecked(
true,
title.to_string(),
vec![]
))
.collect() // Necessary to create a Vec
)
.exec()
.await?;
跳过重复项
create_many
构建器有一个 skip_duplicates
函数,如果违反唯一约束,可以使用该函数停止抛出错误,否则将忽略冲突的记录并创建其余记录。
client
.post()
.create_many(..)
.skip_duplicates() // No error if unique violation is broken
.exec()
.await?