sql - 在使用 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,但这也不起作用。
我不确定如何选择要返回的数据,并按最大计数排序。任何帮助将不胜感激。
解决方案
您需要使用 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,
},
})
推荐阅读
- r - 如何将频谱图矩阵转换为 wav 文件
- json - 如何在json-schema Scala中为每个对象添加additionalProperties:false
- javascript - React.JS + axios 在 initialState 中解析错误。安装了axios
- python-3.x - 使用 django-rest-auth 和 allauth 进行 Google 身份验证
- javascript - Cloudinary 视频集成反应找不到元素 ID
- java - GRPC ConnectivityState 不能正常工作?
- amazon-web-services - 已解决 AWS CloudFormation 创建堆栈。未解决的资源依赖关系
- java - 为立即加入 JDA 的用户 jda 赋予角色的最佳方式是什么
- javascript - 找不到模块“./App.svelte”或其对应的类型声明
- reactjs - React 中 Material UI DatePicker 中的最小和最大日期