我正在尝试使用strapi为费用记录构建一个api。我有旅行,每一次旅行都有多笔费用。(一对多关系)。我希望,当我去/trips的时候,它也会给我那次旅行的所有费用的总和。(每笔费用都有适当的金额)我只需要sumField作为响应,而不是在api的模型上(所以我不能修改它)。我正在使用postrgres。很明显,我必须修改控制器,找到并找到一个,但我不知道如何求和。
此外,如果可以从graphql中查询它。有什么帮助吗?
发布于 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
然后在你的控制器中,你会看到类似这样的东西:
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;
}
};发布于 2019-10-05 22:12:09
谢谢。我会尽力的。如果费用是一个关系字段,该怎么办?旅行会有很多开销。
https://stackoverflow.com/questions/58233341
复制相似问题