Group by with Sequelize

编程入门 行业动态 更新时间:2024-10-08 20:36:43

<a href=https://www.elefans.com/category/jswz/34/1768218.html style=Group by with Sequelize"/>

Group by with Sequelize

我具有以下类结构:

[我正在尝试按Sequelize分组并计数,Cup_Selections表中每个选择所具有的标题等于下面键入的查询的数量:

使用Sequelize进行我的Node查询如下:

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

但是向我显示以下错误:

(node:28230) UnhandledPromiseRejectionWarning: SequelizeDatabaseError: column "Champion.id" must appear in the GROUP BY clause or be used in an aggregate function

我该如何解决?

回答如下:我如下解决:

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

更多推荐

Group by with Sequelize

本文发布于:2024-05-07 05:04:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1754389.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Group   Sequelize

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!