Strapi:获取深层嵌套关系的所有嵌套属性

Strapi: Get all nested properties for deeply nested relation

我最近开始使用 strapi 并一直在弄清楚如何处理内容关系等等......现在我已经达到了多个内容关系相互依赖的地步。

这是我的结构:

集合类型:

  1. 类别
  2. 文章
    • 与内容关系:文章有一个类别

单一类型:

  1. 首页
    • 与内容关系:主页有很多文章

现在我想做的是通过简单地从 /homepage

发出 GET 请求来获取分配给主页的文章的类别的所有嵌套属性

我目前得到的是一个json这样的结构:

{
   "id": 1,
   "hero": {
    ....
   },
   "featuredArticles": {
    ....
   },
   "displayedArticles": [
      {
         "id": 2,
         "category": 5,
      }
   ]
}

预期输出是什么:

{
   "id": 1,
   "hero": {
    ....
   },
   "featuredArticles": {
    ....
   },
   "displayedArticles": [
      {
         "id": 2,
         "category": [
            {
              "id": 5,
              "title": "Foundation"
            }
         ],
      }
   ]
}

我怀疑当尝试从 /homepage 而不是直接从 /articles 获取时,类别的属性基本上过于嵌套了。

我发现可以通过修改 strapi 目录中的控制器来处理这个问题,但我还没有弄明白。

Strapi Controller Docs

这里有人知道解决这个问题的方法吗?

首先,您需要一个自定义控制器函数。在 /api/homepage/controllers/homepage.js 中,您可以导出自定义查找功能。

您可以在此处定义要填充的字段:

module.exports = {
 find: ctx => {
   return strapi.query('homepage').find(ctx.query, [
     {
       path: 'displayedArticles',
       populate: {
         path: 'category',
       },
     },
   ]);
 }
};

有关参考,请参阅最新的测试版文档: Customization

第二种方式:根据要求填充它

module.exports = {
  find: async (ctx) => {
    const homePage = await strapi.query('homepage').find(ctx.query);
    const categories = await strapi.query('categories').find();

    if (homePage[0].displayedArticles) {
       homePage[0].displayedArticles.forEach(async (content) => {
         if(categories){
           content.category = categories.find((category) => {
             return category.id === content.category;
           });
         }
      });
    } 
    
    if (homePage[0].displayedComponents) {
      homePage[0].displayedComponents.forEach(async (content) => {
        if(categories){
         content.category = categories.find((category) => {
           return category.id === content.category;
          });
        }
      });
    } 
    
    return homePage;
  }

};