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

时间:2021-04-12 10:38:39

标签: javascript json strapi

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

这是我的结构:

集合类型:

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

单一类型:

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

现在我想要做的是获取分配给主页的文章的类别的所有嵌套属性,只需从 GET

发出 /homepage 请求

我目前得到的是这样的 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

这里有人知道解决方案吗?

1 个答案:

答案 0 :(得分:0)

首先,您需要一个自定义控制器功能。在 /api/homepage/controllers/homepage.js 中,您可以导出自定义查找功能。您可以在那里定义要填充的字段:

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

For reference see the most recent beta docs: [Customization][1]



  [1]: https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#queries

Second way:
or you can populate it as per requirement:

        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;
        }

  };
相关问题