首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >某个字段的Strapi sum值

某个字段的Strapi sum值
EN

Stack Overflow用户
提问于 2019-10-04 17:12:49
回答 2查看 899关注 0票数 0

我正在尝试使用strapi为费用记录构建一个api。我有旅行,每一次旅行都有多笔费用。(一对多关系)。我希望,当我去/trips的时候,它也会给我那次旅行的所有费用的总和。(每笔费用都有适当的金额)我只需要sumField作为响应,而不是在api的模型上(所以我不能修改它)。我正在使用postrgres。很明显,我必须修改控制器,找到并找到一个,但我不知道如何求和。

此外,如果可以从graphql中查询它。有什么帮助吗?

EN

回答 2

Stack Overflow用户

发布于 2019-10-04 21:42:57

确切地说,您必须定制您的API以添加新的路由和控制器(以保留当前默认的API内容),以返回您所需要的内容。

首先,您必须在所需的API中创建一个路由和一个控制器。在你的情况下。这里有一个名为hello - replace hello by post的API的文档。https://strapi.io/documentation/3.0.0-beta.x/guides/controllers.html#custom-controllers

然后在你的控制器中,你会看到类似这样的东西:

代码语言:javascript
复制
const { sanitizeEntity } = require('strapi-utils');

module.exports = {
  async tripsWithSum (ctx) {
    let entities;
    if (ctx.query._q) {
      entities = await strapi.services.trip.search(ctx.query);
    } else {
      entities = await strapi.services.trip.find(ctx.query);
    }

    entities = entities.map(entity => sanitizeEntity(entity, { model: Trip }));

    entities = entities.map(entry => {
      entry = Object.assign(entry, {
        sumField: entry.expenses.length
      });
    });

    return entities;
  }
};
票数 0
EN

Stack Overflow用户

发布于 2019-10-05 22:12:09

谢谢。我会尽力的。如果费用是一个关系字段,该怎么办?旅行会有很多开销。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58233341

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档