You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Strapi中实现按字段分组并统计相同值条目数量?

Strapi实现投票结果分组统计方案

核心结论

Strapi的默认REST/GraphQL API不支持开箱即用的分组统计功能,需要通过自定义控制器扩展实现。

实现方法

方法一:使用Knex查询构建器(推荐)

在Strapi的Response集合控制器中添加自定义方法,利用Knex的分组查询能力实现统计:

// api/response/controllers/response.js
module.exports = {
  async getVoteStats(ctx) {
    const stats = await strapi.db.query('api::response.response').model.query((qb) => {
      qb.select('answer', strapi.db.connection.raw('count(*) as total'))
        .groupBy('answer');
    }).fetchAll();
    return stats.toJSON();
  }
};

添加完成后,可在路由配置中新增接口路径,前端即可通过该接口获取格式符合要求的统计结果。

方法二:执行原生SQL

如果更偏好原生SQL写法,可直接通过Strapi的数据库连接执行查询:

// api/response/controllers/response.js
module.exports = {
  async getVoteStats(ctx) {
    const [results] = await strapi.db.connection.raw(
      'SELECT answer, COUNT(*) as total FROM responses GROUP BY answer'
    );
    return results;
  }
};

结果说明

上述两种方法返回的数据格式均与你期望的一致:

[
  { "answer": "a", "total": 3 },
  { "answer": "b", "total": 1 }
]

内容的提问来源于stack exchange,提问作者Kelvin Barsana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 12:25:40