Skip to main content

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

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

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

¥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.

注意

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 文件。

    ¥Open the content-type schema.json file.

  2. "populateCreatorFields": true 添加到 options 对象:

    ¥Add "populateCreatorFields": true to the options object:

  "options": {
"draftAndPublish": true,
"populateCreatorFields": true
},
  1. 保存 schema.json

    ¥Save the schema.json.

  2. 使用 生成 CLI 或通过在 ./src/api/[content-type-name]/middlewares/[your-middleware-name].js 中手动创建新文件来创建新的路由中间件

    ¥Create a new route middleware either using the generate CLI or by manually creating a new file in ./src/api/[content-type-name]/middlewares/[your-middleware-name].js

  3. 添加以下代码,你可以修改此示例以满足你的需要:

    ¥Add the following piece of code, you can modify this example to suit your needs:

./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. 修改你的默认路由工厂,以在你希望此群体应用的特定路由上启用此中间件,并将内容类型/中间件名称替换为你的内容类型/中间件名称:

    ¥Modify your default route factory to enable this middleware on the specific routes you want this population to apply to and replacing the content-type/middleware name with yours:

./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.