Skip to main content
Unlisted page
This page is unlisted. Search engines will not index it, and only users having a direct link can access it.

使用查询引擎 API 填充

¥Populating with the Query Engine API

提醒

在大多数情况下,你不应使用查询引擎 API,而应使用 文档服务 API

¥In most cases you should not use the Query Engine API and rather use the Document Service API.

仅当你确切知道自己在做什么时才使用查询引擎 API,例如,如果你想使用直接与数据库的唯一行交互的底层 API。

¥Only use the Query Engine API if you exactly know what you are doing, for instance if you want to use a lower-level API that directly interacts with unique rows of the database.

请记住,查询引擎 API 不了解最高级的 Strapi 5 功能,如草稿和发布、国际化、内容历史记录等。这也意味着查询引擎 API 将无法使用 documentId,而将使用 id,这意味着它可能导致数据库级别出现意外后果,或者与 Strapi 5 功能部分或不完全兼容。

¥Please keep in mind that the Query Engine API is not aware of the most advanced Strapi 5 features like Draft & Publish, Internationalization, Content History, and possibly more. This also means that the Query Engine API will not be able to use documentId and will use id, which means it could lead to unattended consequences at the database level or partial or incomplete compatibility with Strapi 5 features.

Prerequisites

在深入了解查询引擎 API 文档之前,建议你阅读以下介绍:

¥Before diving deeper into the Query Engine API documentation, it is recommended that you read the following introductions:

关系和组件有一个统一的 API 来填充它们。

¥Relations and components have a unified API for populating them.

要填充所有根级别关系,请使用 populate: true

¥To populate all the root level relations, use populate: true:

strapi.db.query('api::article.article').findMany({
populate: true,
});

通过传递属性名称数组来选择要填充的数据:

¥Select which data to populate by passing an array of attribute names:

strapi.db.query('api::article.article').findMany({
populate: ['componentA', 'relationA'],
});

可以传递一个对象以进行更高级的用法:

¥An object can be passed for more advanced usage:

strapi.db.query('api::article.article').findMany({
populate: {
componentB: true,
dynamiczoneA: true,
relation: someLogic || true,
},
});

复杂的填充也可以通过应用 where 过滤器并选择或填充嵌套关系来实现:

¥Complex populating can also be achieved by applying where filters and select or populate nested relations:

strapi.db.query('api::article.article').findMany({
populate: {
relationA: {
where: {
name: {
$contains: 'Strapi',
},
},
},

repeatableComponent: {
select: ['someAttributeName'],
orderBy: ['someAttributeName'],
populate: {
componentRelationA: true,
},
},

dynamiczoneA: true,
},
});

在处理多态内容结构(动态区域、多态关系等)时,可以使用填充片段来更好地控制填充策略。

¥When dealing with polymorphic content structures (dynamic zones, polymorphic relations, etc...), it is possible to use populate fragments to have a better granularity on the populate strategy.

strapi.db.query('api::article.article').findMany('api::article.article', {
populate: {
dynamicZone: {
on: {
'components.foo': {
select: ['title'],
where: { title: { $contains: 'strapi' } },
},
'components.bar': {
select: ['name'],
},
},
},

morphAuthor: {
on: {
'plugin::users-permissions.user': {
select: ['username'],
},
'api::author.author': {
select: ['name'],
},
},
},
},
});