🛠️ 如何填充创作者字段,例如 createdBy 和 updatedBy
🌐 🛠️ How to populate creator fields such as createdBy and updatedBy
创建者字段 createdBy 和 updatedBy 默认从 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.
populateCreatorFields 属性在 GraphQL API 中不可用。
🌐 The populateCreatorFields property is not available to the GraphQL API.
只有以下字段会被填充:id、firstname、lastname、username、preferedLanguage、createdAt 和 updatedAt。
🌐 Only the following fields will be populated: id, firstname, lastname, username, preferedLanguage, createdAt, and updatedAt.
将 createdBy 和 updatedBy 添加到 API 响应中:
🌐 To add createdBy and updatedBy to the API response:
- 打开内容类型为
schema.json的文件。 - 将
"populateCreatorFields": true添加到options对象中:
"options": {
"draftAndPublish": true,
"populateCreatorFields": true
},
- 保存
schema.json。 - 可以使用 generate CLI 创建一个新的路由中间件,或者通过在
./src/api/[content-type-name]/middlewares/[your-middleware-name].js中手动创建一个新文件来实现 - 添加以下代码,你可以修改此示例以满足你的需要:
"use strict";
module.exports = (config, { strapi }) => {
return async (ctx, next) => {
if (!ctx.query.populate) {
ctx.query.populate = ["createdBy", "updatedBy"];
}
await next();
};
};
- 修改你的默认路由工厂,以在你希望此群体应用的特定路由上启用此中间件,并将内容类型/中间件名称替换为你的内容类型/中间件名称:
"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 请求默认会包含 createdBy 或 updatedBy 字段。
🌐 REST API requests with no populate parameter will include the createdBy or updatedBy fields by default.