Prisma 3 关系聚合(总和)
Posted
技术标签:
【中文标题】Prisma 3 关系聚合(总和)【英文标题】:Prisma 3 relation aggregation (sum) 【发布时间】:2021-12-15 15:55:38 【问题描述】:我在获取相关数据的总和时遇到了一些麻烦。
这是我的架构:
model Vote
userId Int
user User @relation(fields: [userId], references: [id])
itemId Int
item Item @relation(fields: [itemId], references: [id])
value Int
@@id([userId, itemId])
model Item
id Int @id @default(autoincrement())
userId Int
user User @relation(fields: [userId], references: [id])
listId Int
list List @relation(fields: [listId], references: [id])
votes Vote[]
body String @db.VarChar(255)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
model List
id Int @id @default(autoincrement())
userId Int
user User @relation(name: "Ownership", fields: [userId], references: [id])
items Item[]
sharedWith User[] @relation(name: "Shared")
title String @db.VarChar(255)
description String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
model User
id Int @id @default(autoincrement())
email String @unique
password String
name String?
lists List[] @relation(name: "Ownership")
items Item[]
votes Vote[]
sharedWith List[] @relation(name: "Shared")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
我想要得到的是:
1 按 ID 列出 包含的列表项 对于每个项目的值总和(来自投票表)。这是我想出的:
prisma.list.findUnique(
where: id ,
include:
items:
include:
votes:
include:
_sum:
select:
value: true,
,
,
,
,
,
,
,
)
我根据我在网上找到的多个不同查询(大部分在 Prisam Docs 中)构建了查询。
我还注意到 Prisma Docs 缺少很多东西,例如(添加/删除相关数据 - 多对多关系)。有没有更好的文档或包含此类内容的示例项目?
谢谢!
【问题讨论】:
【参考方案1】:目前无法将其作为单个查询。您可以做的是在取回这些值后对它们进行求和。
我基于 *** 创建了一个类似的示例。给定以下 Prisma Schema:
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
datasource db
provider = "postgresql"
url = env("DATABASE_URL")
generator client
provider = "prisma-client-js"
model User
id Int @id @default(autoincrement())
name String
votes Vote[]
questions Question[]
model Question
id Int @id @default(autoincrement())
question String
votes Vote[]
user User @relation(fields: [userId], references: [id])
userId Int
model Vote
id Int @id @default(autoincrement())
value Int @default(1)
questionId Int
question Question @relation(fields: [questionId], references: [id])
user User @relation(fields: [userId], references: [id])
userId Int
您可以编写以下脚本:
import PrismaClient from "@prisma/client"
const prisma = new PrismaClient()
async function main()
const users = await prisma.user.findMany(
include:
questions:
include:
votes:
select:
value: true,
,
,
,
,
,
)
for (let user of users)
for (let question of user.questions)
let vote_sum = 0
for (let vote of question.votes)
vote_sum += vote.value
;(question as any).vote_sum = vote_sum
console.dir(users, depth: Infinity )
main().catch((err) => console.error(err))
然后在取回数据后对这些值求和。
如果这不适合您,我建议您为 Prisma 团队写一封 feature request。
【讨论】:
以上是关于Prisma 3 关系聚合(总和)的主要内容,如果未能解决你的问题,请参考以下文章