使用查询引擎 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 功能,如草稿和发布、国际化、内容历史记录等。
¥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.
关系和组件有一个统一的 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 data 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'],
},
},
},
},
});