获取关联数据
可以通过调用查询构建器的 with
函数来获取关联数据。关联字段的字段模块将包含 fetch
函数,其结果可以传递给 with
。多对多关联的 fetch
函数接受一个 Vec
的 WhereParam
,而单一关联的 fetch
函数不接受任何参数。
获取关联数据后,可以通过两种方式访问
-
(推荐) 在父结构体上使用关联访问函数。这些函数将返回一个包含对关联数据的引用的
Result
。这是推荐的方法,因为Result
的错误类型将告知您该字段尚未使用with
获取。 -
直接在父结构体上使用数据。这使您可以直接访问关联数据,其中它包装在
Option
中以确定它是否已被获取。仅当您需要获取关联数据的所有权时才推荐这样做,因为处理嵌套选项可能很棘手,并且不如访问器函数提供的错误描述性强。
只有在访问器的 Result
无法 panic 时才能在编译时保证关联是否已加载 - 即未在其上调用 unwrap
、expect
等。请参阅 选择 & 包含 以获取获取关联数据的完全类型安全的方法。
示例使用以下模式
model Post {
id String @id @default(cuid())
published Boolean
title String
content String?
desc String?
comments Comment[]
}
model Comment {
id String @id @default(cuid())
content String
post Post @relation(fields: [postID], references: [id])
postID String
}
单一关联
在此示例中,post
关联与评论一起加载。
use prisma::{comment, post};
let comment: Option<comment::Data> = client
.comment()
.find_unique(comment::id::equals("0".to_string()))
.with(comment::post::fetch())
.exec()
.await
.unwrap();
// Since the above query includes a with() call
// the result will be an Ok()
let post: Result<post::Data, String> = comment.post();
多对多关联
在此示例中,加载了一个 post
及其 comments
。
use prisma::{comment, post};
let post: Option<post::Data> = client
.post()
.find_unique(post::id::equals("0".to_string()))
// Many relation requires Vec of filters as argument
.with(post::comments::fetch(vec![]))
.exec()
.await
.unwrap();
let comments: Result<Vec<comment::Data>, String> = post.comments();
嵌套关联
fetch
返回一个查询构建器,因此您可以嵌套像 with
这样的调用来获取嵌套关联。
在此示例中,加载了一个帖子及其评论,并且每个评论都与原始帖子一起加载。
use prisma::{comment, post};
let post: post::Data = client
.post()
.find_unique(post::id::equals("0".to_string()))
.with(post::comments::fetch(vec![])
.with(comment::post::fetch())
)
.exec()
.await
.unwrap()
.unwrap();
// Safe since post::comments::fetch has been used
for comment in post.comments().unwrap() {
// Safe since comment::post::fetch has been used
let post = comment.post().unwrap();
assert_eq!(post.id, "0");
}