使用查询引擎 API 进行单条操作

页面摘要: 查询引擎 API 提供了查找、创建、更新与删除单条条目的方法,并支持过滤、字段选择、分页与关联联表加载等选项。

WARNING

大多数情况下你不应使用 Query Engine API,而应使用 Document Service API。

只有当你能确定自己在做什么时才使用 Query Engine API,例如需要直接与数据库唯一行交互的底层 API。

请注意,Query Engine API 无法感知 Strapi 5 的高级功能,如草稿与发布、国际化、内容历史等。这也意味着 Query Engine API 无法使用 documentId,而会使用 id,这可能导致数据库层面的意外后果,或与 Strapi 5 功能出现部分或不完整的兼容性问题。

WARNING

在深入阅读 Query Engine API 文档之前,建议你先阅读以下介绍:

findOne()

NOTE

仅当 文档服务的 findOne() 方法无法满足你的使用场景时,才使用查询引擎的 findOne() 方法。 查找与参数匹配的第一个条目。

语法:findOne(parameters) ⇒ Entry

参数

参数类型说明
selectString,或 Array of strings需返回的 属性
whereWhereParameter要使用的 过滤器
offsetInteger要跳过的条目数
orderByOrderByParameter排序 定义
populatePopulateParameter要 联表加载 的关联

示例

const entry = await strapi.db.query('api::blog.article').findOne({
  select: ['title', 'description'],
  where: { title: 'Hello World' },
  populate: { category: true },
});

findMany()

NOTE

仅当 文档服务的 findMany() 方法无法满足你的使用场景时,才使用查询引擎的 findMany() 方法。

查找与参数匹配的条目。

语法:findMany(parameters) ⇒ Entry[]

参数

参数类型说明
selectString,或 Array of strings需返回的 属性
whereWhereParameter要使用的 过滤器
limitInteger需返回的条目数
offsetInteger要跳过的条目数
orderByOrderByParameter排序 定义
populatePopulateParameter要 联表加载 的关联

示例

const entries = await strapi.db.query('api::blog.article').findMany({
  select: ['title', 'description'],
  where: { title: 'Hello World' },
  orderBy: { publishedAt: 'DESC' },
  populate: { category: true },
});

findWithCount()

查找并统计与参数匹配的条目。

语法:findWithCount(parameters) => [Entry[], number]

参数

参数类型说明
selectString,或 Array of strings需返回的 属性
whereWhereParameter要使用的 过滤器
limitInteger需返回的条目数
offsetInteger要跳过的条目数
orderByOrderByParameter排序 定义
populatePopulateParameter要 联表加载 的关联

示例

const [entries, count] = await strapi.db.query('api::blog.article').findWithCount({
  select: ['title', 'description'],
  where: { title: 'Hello World' },
  orderBy: { title: 'DESC' },
  populate: { category: true },
});

create()

NOTE

仅当 文档服务的 create() 方法 无法满足你的使用场景时,才使用查询引擎的 create() 方法。

创建一个条目并返回。

语法:create(parameters) => Entry

参数

参数类型说明
selectString,或 Array of strings需返回的 属性
populatePopulateParameter要 联表加载 的关联
data对象输入数据

示例

const entry = await strapi.db.query('api::blog.article').create({
  data: {
    title: 'My Article',
  },
});

update()

NOTE

仅当 文档服务的 update() 方法无法满足你的使用场景时,才使用查询引擎的 update() 方法。

更新一个条目并返回。

语法:update(parameters) => Entry

参数

参数类型说明
selectString,或 Array of strings需返回的 属性
populatePopulateParameter要 联表加载 的关联
whereWhereParameter要使用的 过滤器
data对象输入数据

示例

const entry = await strapi.db.query('api::blog.article').update({
  where: { id: 1 },
  data: {
    title: 'xxx',
  },
});

delete()

NOTE

仅当 文档服务的 delete() 方法无法满足你的使用场景时,才使用查询引擎的 delete() 方法。

删除一个条目并返回。

语法:delete(parameters) => Entry

参数

参数类型说明
selectString,或 Array of strings需返回的 属性
populatePopulateParameter要 联表加载 的关联
whereWhereParameter要使用的 过滤器

示例

const entry = await strapi.db.query('api::blog.article').delete({
  where: { id: 1 },
});