使用查询引擎 API 批量操作
🌐 Bulk Operations 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.
在深入了解查询引擎 API 文档之前,建议你阅读以下介绍:
🌐 Before diving deeper into the Query Engine API documentation, it is recommended that you read the following introductions:
为了避免性能问题,不允许对关系进行批量操作。
🌐 To avoid performance issues, bulk operations are not allowed on relations.
createMany()
创建多个条目。
🌐 Creates multiple entries.
语法:createMany(parameters) => { count: number, ids: id[] }
🌐 Syntax: createMany(parameters) => { count: number, ids: id[] }
参数
🌐 Parameters
| 参数 | 类型 | 描述 || --- | --- | --- || data | 对象数组 | 输入数据数组 |
- MySQL 将仅返回包含最后插入的 id 的一个 id 数组,而不是整个列表。
- 在 Strapi v4.9.0 之前,
createMany()只会返回count。
例子
🌐 Example
await strapi.db.query("api::blog.article").createMany({
data: [
{
title: "ABCD",
},
{
title: "EFGH",
},
],
});
// { count: 2 , ids: [1,2]}
updateMany()
更新与参数匹配的多个条目。
🌐 Updates multiple entries matching the parameters.
语法:updateMany(parameters) => { count: number }
🌐 Syntax: updateMany(parameters) => { count: number }
参数
🌐 Parameters
| 参数 | 类型 | 描述 || --- | --- | --- || where | WhereParameter | 要使用的过滤器 || data | 对象 | 输入数据 |
例子
🌐 Example
await strapi.db.query("api::shop.article").updateMany({
where: {
price: 20,
},
data: {
price: 18,
},
});
// { count: 42 }
deleteMany()
删除与参数匹配的多个条目。
🌐 Deletes multiple entries matching the parameters.
语法:deleteMany(parameters) => { count: number }
🌐 Syntax: deleteMany(parameters) => { count: number }
参数
🌐 Parameters
| 参数 | 类型 | 描述 || --- | --- | --- || where | WhereParameter | 使用的过滤器 |
例子
🌐 Example
await strapi.db.query("api::blog.article").deleteMany({
where: {
title: {
$startsWith: "v3",
},
},
});
// { count: 42 }
聚合
🌐 Aggregations
count()
计算与参数匹配的条目数。
🌐 Counts entries matching the parameters.
语法:count(parameters) => number
🌐 Syntax: count(parameters) => number
参数
🌐 Parameters
| 参数 | 类型 | 描述 || --- | --- | --- || where | WhereParameter | 使用的过滤器 |
const count = await strapi.db.query("api::blog.article").count({
where: {
title: {
$startsWith: "v3",
},
},
});
// 12