Skip to main content

🛠️ 如何填充创作者字段,例如 createdByupdatedBy

🌐 🛠️ How to populate creator fields such as createdBy and updatedBy

创建者字段 createdByupdatedBy 默认从 REST API 响应中移除。通过在内容类型级别激活 populateCreatorFields 参数,这两个字段可以在 REST API 中返回。

🌐 The creator fields createdBy and updatedBy are removed from the REST API response by default. These 2 fields can be returned in the REST API by activating the populateCreatorFields parameter at the content-type level.

Note

populateCreatorFields 属性在 GraphQL API 中不可用。

🌐 The populateCreatorFields property is not available to the GraphQL API.

只有以下字段会被填充:idfirstnamelastnameusernamepreferedLanguagecreatedAtupdatedAt

🌐 Only the following fields will be populated: id, firstname, lastname, username, preferedLanguage, createdAt, and updatedAt.

createdByupdatedBy 添加到 API 响应中:

🌐 To add createdBy and updatedBy to the API response:

  1. 打开内容类型为 schema.json 的文件。
  2. "populateCreatorFields": true 添加到 options 对象中:
"options": {
"draftAndPublish": true,
"populateCreatorFields": true
},
  1. 保存 schema.json
  2. 可以使用 generate CLI 创建一个新的路由中间件,或者通过在 ./src/api/[content-type-name]/middlewares/[your-middleware-name].js 中手动创建一个新文件来实现
  3. 添加以下代码,你可以修改此示例以满足你的需要:
./src/api/test/middlewares/defaultTestPopulate.js
"use strict";

module.exports = (config, { strapi }) => {
return async (ctx, next) => {
if (!ctx.query.populate) {
ctx.query.populate = ["createdBy", "updatedBy"];
}

await next();
};
};
  1. 修改你的默认路由工厂,以在你希望此群体应用的特定路由上启用此中间件,并将内容类型/中间件名称替换为你的内容类型/中间件名称:
./src/api/test/routes/test.js
"use strict";

const { createCoreRouter } = require("@strapi/strapi").factories;

module.exports = createCoreRouter("api::test.test", {
config: {
find: {
middlewares: ["api::test.default-test-populate"],
},
findOne: {
middlewares: ["api::test.default-test-populate"],
},
},
});

没有 populate 参数的 REST API 请求默认会包含 createdByupdatedBy 字段。

🌐 REST API requests with no populate parameter will include the createdBy or updatedBy fields by default.