Barelydead / strapi-plugin-populate-deep

A Strapi plugin that makes it easier to populate deep content structures
172 stars 39 forks source link

How to implement this Plugin on Custom Controllers? #34

Open MO-Lewis opened 1 year ago

MO-Lewis commented 1 year ago

Hi there,

I'm expanding Strapi 4's controllers to use some custom filtering. However, looking at the GitHub page, all of the example implementation appears to only include using the "?populate=deep" param on the initial request that gets sent to Strapi.

I would like to implement it in a custom controller. I'm using the Strapi QueryEngine, (Not the entityService, although they're pretty similar.).

For example, I'd like something along the lines of:

const onlyArticles = await strapi.db
  .query("api::article.article")
  .findMany({
    where: {
      .......
    },
    populate: 'deep'
  });

Is this already possible? Or is it something not currently possible in this plugin?

Thanks in advance!

MO-Lewis commented 1 year ago

A quick update before I forget! To do what I've described, you must use the Strapi EntityService on a custom controller, not the QueryEngine.

So instead of:

const onlyArticles = await strapi.db
  .query("api::article.article")
  .findMany({
    where: {
      .......
    },
    populate: 'deep'
  }
);

You should do:

const onlyArticles = await strapi.entityService.findMany(
  "api::article.article",
  {
    where: {
      .......
    },
    populate: "deep",
  }
);

This appears to work as I'd like.

I'll leave the issue open for you to review before you close it, but it would be nice if you could mention this somewhere on the README to help the next person that asks for this :)

Barelydead commented 1 year ago

Thanks for sharing what works. I actially didnt know this would work myself. Cheers