这是用户在 2024-6-6 8:55 为 https://docs.strapi.io/dev-docs/api/rest/populate-select#field-selection 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?
Skip to main content
跳到主要内容

REST API: Population & Field Selection
REST API:人口和字段选择

The REST API by default does not populate any relations, media fields, components, or dynamic zones. Use the populate parameter to populate specific fields and the select parameter to return only specific fields with the query results. Ensure that the find permission is given to the field(s) for the relation(s) you populate.
默认情况下,REST API 不会填充任何关系、媒体字段、组件或动态区域。使用 populate 该参数填充特定字段,使用该 select 参数仅返回包含查询结果的特定字段。确保将查找权限授予您填充的关系的字段。

💡 Tip 💡提示

Strapi takes advantage of the ability of the qs library to parse nested objects to create more complex queries.
Strapi 利用 qs 库解析嵌套对象的能力来创建更复杂的查询。

Use qs directly to generate complex queries instead of creating them manually. Examples in this documentation showcase how you can use qs.
直接用于 qs 生成复杂的查询,而不是手动创建查询。本文档中的示例演示了如何使用 qs .

You can also use the interactive query builder if you prefer playing with our online tool instead of generating queries with qs on your machine.
如果您更喜欢使用我们的在线工具而不是 qs 在您的机器上生成查询,您也可以使用交互式查询构建器。

Field selection 字段选择

Queries can accept a fields parameter to select only some fields. By default, only the following types of fields are returned:
查询可以接受 fields 参数以仅选择某些字段。默认情况下,仅返回以下类型的字段:

  • string types: string, text, richtext, enumeration, email, password, and uid,
    字符串类型:字符串、文本、富文本、枚举、电子邮件、密码和 UID、
  • date types: date, time, datetime, and timestamp,
    日期类型:日期、时间、日期时间和时间戳,
  • number types: integer, biginteger, float, and decimal,
    数字类型:整数、大整数、浮点数和十进制,
  • generic types: boolean, array, and JSON.
    泛型类型:boolean、array 和 JSON。

Field selection does not work on relational, media, component, or dynamic zone fields. To populate these fields, use the populate parameter.
字段选择不适用于关系区域、媒体、组件或动态区域字段。若要填充这些字段,请使用参数 populate

💡 Tip 💡提示

By default, fields are selected except relations, media, dynamic zones, and components, but you can specify a wildcard * instead of an array.
默认情况下,除关系、媒体、动态区域和组件之外,字段处于选中状态,但您可以指定通配符 * 而不是数组。



Example request: Return only title and body fields
示例请求:仅返回标题和正文字段

GET /api/users?fields[0]=title&fields[1]=body

Example response 响应示例
{
"data": [
{
"id": 1,
"attributes": {
"title": "test1",
"body": "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
}
}
],
"meta": {
// ...
}
}

JavaScript query (built with the qs library):
JavaScript 查询(使用 qs 库构建):

The query URL above was built using the qs library. qs can be run locally on your machine, as shown in the following code example, or you can use our interactive query builder online tool.

const qs = require('qs');
const query = qs.stringify(
{
fields: ['title', 'body'],
},
{
encodeValuesOnly: true, // prettify URL
}
);

await request(`/api/users?${query}`);

Population 人口

The REST API by default does not populate any type of fields, so it will not populate relations, media fields, components, or dynamic zones unless you pass a populate parameter to populate various field types.
默认情况下,REST API 不会填充任何类型的字段,因此它不会填充关系、媒体字段、组件或动态区域,除非您传递参数 populate 来填充各种字段类型。

The populate parameter can be used alone or in combination with with multiple operators to have much more control over the population.
populate 参数可以单独使用,也可以与多个运算符结合使用,以便更好地控制总体。

Caution ✋谨慎

The find permission must be enabled for the content-types that are being populated. If a role doesn't have access to a content-type it will not be populated (see User Guide for additional information on how to enable find permissions for content-types).
必须为要填充的内容类型启用该 find 权限。如果角色无权访问内容类型,则不会填充该角色(有关如何为内容类型启用 find 权限的其他信息,请参阅用户指南)。

✏️ Note ✏️注意

It's currently not possible to return just an array of ids with a request.
目前无法仅返回带有请求的 ID 数组。

🤓 Populating guides 🤓填充指南

The REST API guides section includes more detailed information about various possible use cases for the populate parameter:
REST API 指南部分包含有关 populate 参数的各种可能用例的更多详细信息:

  • The Understanding populate guide explains in details how populate works, with diagrams, comparisons, and real-world examples.
    了解填充指南通过图表、比较和实际示例详细解释了填充的工作原理。
  • The How to populate creator fields guide provides step-by-step instructions on how to add createdBy and updatedBy fields to your queries responses.
    如何填充创建者字段指南提供了有关如何向查询响应添加 createdBy 字段的 updatedBy 分步说明。

The Strapi Blog also includes a tutorial on how to populate and filter data with your queries.
Strapi 博客还包括一个关于如何使用查询填充和筛选数据的教程。

The following table sums up possible populate use cases and their associated parameter syntaxes, and links to sections of the Understanding populate guide which includes more detailed explanations:
下表总结了可能的填充用例及其关联的参数语法,并链接到了解填充指南的各个部分,其中包括更详细的说明:

Use case 用例Example parameter syntax 示例参数语法Detailed explanations to read
详细解释阅读
Populate everything, 1 level deep, including media fields, relations, components, and dynamic zones
填充所有内容,深度为 1 级,包括媒体字段、关系、组件和动态区域
populate=*Populate all relations and fields, 1 level deep
填充所有关系和字段,深度为 1 级
Populate one relation, 填充一个关系,
1 level deep 1层深
populate[0]=a-relation-namePopulate 1 level deep for specific relations
为特定关系填充 1 个深度级别
Populate several relations,
填充多个关系,

1 level deep 1层深
populate[0]=relation-name&populate[1]=another-relation-name&populate[2]=yet-another-relation-namePopulate 1 level deep for specific relations
为特定关系填充 1 个深度级别
Populate some relations, several levels deep
填充一些关系,深度为几个级别
populate[first-level-relation-to-populate][populate][0]=second-level-relation-to-populatePopulate several levels deep for specific relations
为特定关系填充多个深度级别
Populate a component 填充组件populate[0]=component-namePopulate components 填充组件
Populate a component and one of its nested components
填充组件及其嵌套组件之一
populate[0]=component-name&populate[1]=component-name.nested-component-namePopulate components 填充组件
Populate a dynamic zone (only its first-level elements)
填充动态区域(仅填充其第一级元素)
populate[0]=dynamic-zone-namePopulate dynamic zones 填充动态区域
Populate a dynamic zone and its nested elements and relations, using a unique, shared population strategy
使用独特的共享人口策略填充动态区域及其嵌套元素和关系
populate[dynamic-zone-name][populate]=*Populate dynamic zones 填充动态区域
Populate a dynamic zone and its nested elements and relations, using a precisely defined, detailed population strategy
使用精确定义的详细人口策略填充动态区域及其嵌套元素和关系
populate[dynamic-zone-name][on][dynamic-zone-name.component-name][populate][relation-name][populate][0]=field-namePopulate dynamic zones 填充动态区域
💡 Tip 💡提示

The easiest way to build complex queries with multiple-level population is to use our interactive query builder tool.
构建具有多级填充的复杂查询的最简单方法是使用我们的交互式查询构建器工具。

Combining Population with other operators 将人口与其他运算符组合

By utilizing the populate operator it is possible to combine other operators such as field selection, filters, and sort in the population queries.
通过使用 populate 运算符,可以在总体查询中组合其他运算符,例如字段选择、过滤器和排序。

Caution ✋谨慎

The population and pagination operators cannot be combined.
population 和 pagination 运算符不能组合。

Populate with field selection
使用字段选择填充

fields and populate can be combined.
fields 并且 populate 可以组合。

Example request 示例请求

GET /api/articles?fields[0]=title&fields[1]=slug&populate[headerImage][fields][0]=name&populate[headerImage][fields][1]=url

Example response 响应示例
{
"data": [
{
"id": 1,
"attributes": {
"title": "Test Article",
"slug": "test-article",
"headerImage": {
"data": {
"id": 1,
"attributes": {
"name": "17520.jpg",
"url": "/uploads/17520_73c601c014.jpg"
}
}
}
}
}
],
"meta": {
// ...
}
}

JavaScript query (built with the qs library):
JavaScript 查询(使用 qs 库构建):

The query URL above was built using the qs library. qs can be run locally on your machine, as shown in the following code example, or you can use our interactive query builder online tool.

const qs = require('qs');
const query = qs.stringify(
{
fields: ['title', 'slug'],
populate: {
headerImage: {
fields: ['name', 'url'],
},
},
},
{
encodeValuesOnly: true, // prettify URL
}
);

await request(`/api/articles?${query}`);

Populate with filtering
使用筛选进行填充

filters and populate can be combined.
filters 并且 populate 可以组合。

Example request 示例请求

GET /api/articles?populate[categories][sort][0]=name%3Aasc&populate[categories][filters][name][$eq]=Cars

Example response 响应示例
{
"data": [
{
"id": 1,
"attributes": {
"title": "Test Article",
// ...
"categories": {
"data": [
{
"id": 2,
"attributes": {
"name": "Cars"
// ...
}
}
]
}
}
}
],
"meta": {
// ...
}
}

JavaScript query (built with the qs library):
JavaScript 查询(使用 qs 库构建):

The query URL above was built using the qs library. qs can be run locally on your machine, as shown in the following code example, or you can use our interactive query builder online tool.

const qs = require('qs');
const query = qs.stringify(
{
populate: {
categories: {
sort: ['name:asc'],
filters: {
name: {
$eq: 'Cars',
},
},
},
},
},
{
encodeValuesOnly: true, // prettify URL
}
);

await request(`/api/articles?${query}`);