写入数据
更新查询

更新查询

示例使用以下模式

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
}

更新

update 接受单个唯一过滤器和一个 Vec 用于应用的更新,并返回更新记录的数据。

以下示例查找并更新现有帖子,并返回结果帖子数据。

use prisma::post;
 
let updated_post: post::Data = client
    .post()
    .update(
        post::id::equals("id".to_string()), // Unique filter
        vec![post::title::set("new title".to_string())] // Vec of updates
    )
    .exec()
    .await?;

更新未经检查

自 v0.6.7 起可用

update_uncheckedupdate 类似,但仅允许使用 UncheckedSetParam 设置标量字段。

use prisma::{comment, post};
 
let comment: comment::Data = client
    .comment()
    .update_unchecked(
        comment::id::equals("some comment id".to_string()),
        // can't `connect` relations, but can set foreign keys directly
        vec![comment::post_id::set("some post id".to_string())]
    )
    .exec()
    .await?;

更新多个

update_many 接受一个 Vec 过滤器(不仅仅是唯一过滤器),以及一个 Vec 用于应用于所有找到的记录的更新。它返回更新的记录数。

以下示例查找并更新一组帖子。返回更新的记录数。

use prisma::post;
 
let updated_posts_count: i64 = client
    .post()
    .update_many(
        vec![post::id::contains("id".to_string())], // Vec of filters
        vec![post::content::set("new content".to_string())] // Updates to be applied to each record
    )
    .exec()
    .await?;

更新关联

使用 connectdisconnect,可以在 update 查询中修改关联。

重要:使用 update_many 以这种方式更新关联将导致查询始终返回错误。为避免这种情况,请直接设置关联的标量字段。正在努力创建更严格的类型以避免这种情况 跟踪

单条记录

以下示例查找评论并断开与其相关的帖子的关联。

use prisma::{comment, post};
 
let updated_comment: comment::Data = client
    .post()
    .update(
        comment::id::equals("id".to_string()),
        vec![comment::post::disconnect()]
    )
    .exec()
    .await?;

多条记录

以下示例查找帖子上的所有评论并更新它们链接到的帖子,但通过直接修改关联列来实现。

use prisma::{comment, post};
 
let updated_comments_count: i64 = client
    .post()
    .update_many(
        vec![comment::post::is(
            post::id::equals("id".to_string())
        )],
        vec![comment::post_id::set("post".to_string())]
    )
    .exec()
    .await?;