Depth
在 Payload 中,文档可以与其他文档建立关联关系。这一特性适用于 Collections 和 Globals。当你查询文档时,可以指定关联文档的填充深度,可以选择完整对象或仅返回其 ID。
通过限制数据库处理量和显著减少返回数据量,深度设置能优化应用性能。由于文档可以无限嵌套或递归关联,控制 API 的填充深度非常重要。
例如,当指定 depth
为 0
时,API 响应可能如下:
{
"id": "5ae8f9bde69e394e717c8832",
"title": "This is a great post",
"author": "5f7dd05cd50d4005f8bcab17"
}
但当 depth
为 1
时,响应可能变为:
{
"id": "5ae8f9bde69e394e717c8832",
"title": "This is a great post",
"author": {
"id": "5f7dd05cd50d4005f8bcab17",
"name": "John Doe"
}
}
重要提示: 深度设置在 GraphQL API 中无效, 因为 GraphQL 的深度取决于查询结构。
本地 API
在 Local API 中指定深度时,可以在查询中使用 depth
选项:
import type { Payload } from 'payload'
const getPosts = async (payload: Payload) => {
const posts = await payload.find({
collection: 'posts',
depth: 2, // highlight-line
})
return posts
}
提醒: 使用 findGlobal
操作时,Globals 的用法与此相同。
REST API
在 REST API 中指定深度时,可以在查询中使用 depth
参数:
fetch('https://localhost:3000/api/posts?depth=2') // highlight-line
.then((res) => res.json())
.then((data) => console.log(data))
提醒: 使用 /api/globals
端点的 Globals 也同样适用。
最大深度
像 Relationship Field 或 Upload Field 这样的字段也可以设置最大深度。如果超过这个深度,无论请求中的深度是多少,都会限制填充深度。
要为字段设置最大深度,可以在字段配置中使用 maxDepth
属性:
{
slug: 'posts',
fields: [
{
name: 'author',
type: 'relationship',
relationTo: 'users',
maxDepth: 2, // highlight-line
}
]
}