首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Group By with Sequelize

Group By with Sequelize
EN

Stack Overflow用户
提问于 2020-05-03 09:34:57
回答 1查看 3.2K关注 0票数 2

我有如下的类结构:

我尝试通过Sequelize对每个选择的Cup_Selections表中的多少个标题进行分组和计数,这些标题与下面输入的查询相同:

带Sequelize的My Node查询如下:

代码语言:javascript
复制
  async index(req, res) {
    const champions = await Champion.findAll({
      attributes: ['id', 'cupselection_id'],
      include: [
        {
          group: ['selection_id', 'champion.id'],
          raw: true,
          model: CupSelection,
          as: 'cupselection',
          attributes: [
            'id',
            'cup_id',
            [fn('count', col('selection_id')), 'vezes'],
          ],
          include: [
            {
              model: Selection,
              as: 'selection',
              attributes: ['id', 'country'],
            },
          ],
        },
      ],
    });

    return res.json(champions);
  }

但是向我显示了以下错误:

代码语言:javascript
复制
(node:28230) UnhandledPromiseRejectionWarning: SequelizeDatabaseError: column "Champion.id" must appear in the GROUP BY clause or be used in an aggregate function

我该怎么解决呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-04 21:17:02

我的解决方法如下:

代码语言:javascript
复制
  async index(req, res) {
    const { page = 1 } = req.query;

    const champions = await Champion.findAll({
      limit: 5,
      offset: (page - 1) * 5,
      order: [[fn('count', col('cupselection.selection.id')), 'DESC']],
      attributes: [[fn('count', col('cupselection.selection.id')), 'vezes']],
      group: ['cupselection.selection.id', 'cupselection.selection.logo.id'],
      raw: true,
      include: [
        {
          model: CupSelection,
          as: 'cupselection',
          attributes: [],
          include: [
            {
              model: Selection,
              as: 'selection',
              attributes: ['id', 'country'],
              include: [
                {
                  model: File,
                  as: 'logo',
                  attributes: ['id', 'path', 'url'],
                },
              ],
            },
          ],
        },
      ],
    });

    return res.json(champions);
  }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61568552

复制
相关文章

相似问题

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