strapi 4 更新时填充
strapi 4 populate when update
有没有办法在更新时填充字段,
...
const response = await cartService.update(id, { data: { items } });
const sanitizedEntity = await this.sanitizeOutput(response, ctx);
return this.transformResponse(sanitizedEntity);
您可以通过在 http PUT
请求调用中附加 populate=[your_relational_field]
作为 query string
来做到这一点。
样品请求
http://localhost:1337/api/cart/2?populate=category
JSON 格式的示例请求正文
{
"data": {
"items": "items data here"
}
}
就这些!您甚至不需要重写控制器中的核心更新方法,查询字符串将直接由StrapiV4
获取。但是如果出于某种原因你已经覆盖了控制器的核心 update
方法,那么你可以简单地将 ctx
实例传递给核心 update
或 findOne
方法,例如下面:
"use strict";
/**
* cart controller
*/
const { createCoreController } = require("@strapi/strapi").factories;
module.exports = createCoreController("api::cart.cart", ({ strapi }) => ({
async update(ctx) {
// let's say you've written some custom logic here
// finally return the response from core update method
const response = await super.update(ctx);
return response;
// OR
// You can even use the core `findOne` method instead
const response = await super.findOne(ctx);
return response;
// OR
// if you've used some other service then you can pass in the populate option to the update method
const response = await cartService.update(id, {data: { items }, populate: "items.product" });
return response;
},
}));
有没有办法在更新时填充字段,
...
const response = await cartService.update(id, { data: { items } });
const sanitizedEntity = await this.sanitizeOutput(response, ctx);
return this.transformResponse(sanitizedEntity);
您可以通过在 http PUT
请求调用中附加 populate=[your_relational_field]
作为 query string
来做到这一点。
样品请求
http://localhost:1337/api/cart/2?populate=category
JSON 格式的示例请求正文
{
"data": {
"items": "items data here"
}
}
就这些!您甚至不需要重写控制器中的核心更新方法,查询字符串将直接由StrapiV4
获取。但是如果出于某种原因你已经覆盖了控制器的核心 update
方法,那么你可以简单地将 ctx
实例传递给核心 update
或 findOne
方法,例如下面:
"use strict";
/**
* cart controller
*/
const { createCoreController } = require("@strapi/strapi").factories;
module.exports = createCoreController("api::cart.cart", ({ strapi }) => ({
async update(ctx) {
// let's say you've written some custom logic here
// finally return the response from core update method
const response = await super.update(ctx);
return response;
// OR
// You can even use the core `findOne` method instead
const response = await super.findOne(ctx);
return response;
// OR
// if you've used some other service then you can pass in the populate option to the update method
const response = await cartService.update(id, {data: { items }, populate: "items.product" });
return response;
},
}));