首页 > 解决方案 > 在使用 Prisma 的选择查询中使用 _count

问题描述

我目前正在重写我的 Discord 机器人,在此过程中,我需要重写所有 SQL 查询并将它们转换为 Prisma 查询。

SQL 查询 I',试图转换为 Prisma: connection.query('SELECT inviterId, count(*) as count FROM invites where serverId = ? AND valid = 1 GROUP BY inviterId ORDER BY count DESC')

我目前有这个:

    let leaderboard = await client.prisma.invites.aggregate({
      _count: {
        inviterId: true,
      },
      where: {
        serverId: message.guildID,
        valid: true,
      },
      orderBy: {
        inviterId: "desc",
      }
    });
    console.log(leaderboard);

这将返回:{ _count: { inviterId: 25 } }

但是,我还需要在选择查询中返回数据。据我所知,在 findMany 查询中无法使用 _count,因此我尝试在聚合查询中使用 select,但这也不起作用。

我不确定如何选择要返回的数据,并按最大计数排序。任何帮助将不胜感激。

标签: sqltypescriptprismaprisma-graphql

解决方案


您需要使用 groupBy API 而不是聚合。

取自 Prisma 文档: https ://www.prisma.io/docs/concepts/components/prisma-client/aggregation-grouping-summarizing

const groupUsers = await prisma.user.groupBy({
  by: ['country'],
  _sum: {
    profileViews: true,
  },
})

推荐阅读