簡體   English   中英

Prisma 3 關系聚合(sum)

[英]Prisma 3 relation aggregation (sum)

我在嘗試獲取相關數據的總和時遇到了一些麻煩。

這是我的架構:

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 缺少很多東西,例如(添加/刪除相關數據 - 多對多關系)。 有沒有更好的文檔,或者像這樣的東西的示例項目?

謝謝!

這目前不可能作為單個查詢。 您可以做的是在取回這些值后對它們求和。

我基於 StackOverflow 創建了一個類似的示例。 鑒於以下 Prisma 架構:

// 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 團隊編寫功能請求

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM