Skip to content
Advertisement

strapi 4 populate when update

Is there an way to populate the field when updating,

...
 const response = await cartService.update(id, { data: { items } });
 const sanitizedEntity = await this.sanitizeOutput(response, ctx);
 return this.transformResponse(sanitizedEntity);


Advertisement

Answer

You can do this, by attaching the populate=[your_relational_field] as the query string in the http PUT request call.

Sample request

http://localhost:1337/api/cart/2?populate=category

Sample request body in JSON format
{
   "data": {
        "items": "items data here"
   }
}

That’s all! You don’t even need to override the core update method in your controller and the query string will directly be picked up by StrapiV4. But in case for some reason you’ve overridden the core update method from the controller, then you can simply pass the ctx instance to the core update or findOne methods like below:

"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;
  },
}));

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement