【问题标题】:Prisma: How to select or include on a Group by?Prisma:如何选择或包含在 Group by 中?
【发布时间】:2022-01-22 15:50:24
【问题描述】:

我有一个名为financial_transaction 的表,其中包含如下数据:

| id | debit | credit | financial_type | payment_id | payment | author_id  |  author 
  1     150      0        Payment             2                     1
  2     0        50       Payment             2                     1                 

所以我希望从这些数据中:

  • payment_id分组。
  • 包括对author的真实。
  • 将所有debitscredits 相加。
  • 显示financial_typepayment_id 等字段。

这就是我想要的:

[
   { 
     payment_id: 2,
     author: {
       first_name: John,
       last_name: Doe
     }
     debit: 150,
     credit: 50,
     financial_type: Payment
   }
]

这也是我的 Prisma Scehma:

enum FinancialType {
  Payment
  Expense
  Withdraw
}

用户表

model User {
  id                             Int                @id @default(autoincrement())
  first_name                     String
  last_name                      String
  saved_payments                 Payment[]
  saved_financial_transactions FinancialTransaction[]
}

付款表

model Payment {
  id                     Int                @id @default(autoincrement())
  payed_price            Decimal
  remaining_price        Decimal?
  price_per_month        Decimal
  financial_transactions FinancialTransaction[]
  author                 User?              @relation(fields: [author_id], references: [id])
  author_id           Int?
}

财务交易表

model FinancialTransaction {
  id                  Int                @id @default(autoincrement())
  debit               Decimal
  credit              Decimal
  financial_type      FinancialType
  payment             Payment            @relation(fields: [payment_id], references: [id])
  payment_id          Int
  author              User?              @relation(fields: [author_id], references: [id])
  author_id           Int?

}

我试图用 prisma groupBy 得到这个,如下所示:

const financia_transactions = wait prisma.$queryRaw`select jsonb_agg(to_jsonb(t)) from
        (
          select payment_id,
                  jsonb_build_object('first_name', u.first_name, 'second_name', u.second_name) author,
                  sum(debit) debit, 
                  sum(credit) credit, 
                  max(financial_type) financial_type,
          from "FinancialTransaction" as ft join "User" u on ft.author_id = u.id
          group by payment_id
        ) t;`;

但这不起作用... 所以我的问题是 prisma 有什么办法可以做到这一点?

【问题讨论】:

    标签: database postgresql prisma


    【解决方案1】:

    使用原生查询。

    select jsonb_agg(to_jsonb(t)) from
    (
     select payment_id, 
            jsonb_build_object('first_name', u.first_name, 'second_name', u.second_name) author, 
            sum(debit) debit, 
            sum(credit) credit, 
            max(financial_type) financial_type
     from financial_transaction ft join "user" u on ft.author_id = u.id
     group by payment_id
    ) t;
    

    【讨论】:

    • 感谢您的回答兄弟,但它说的是column \"author\" does not exist.... 如果您以某种方式与用户表中的该作者合作,我可能会提醒您。这意味着have 1-many relationship with paymnets 这就是我在上表中留空的原因
    • btw author 列将所有用户数据作为对象。
    • 那么,不管是不是棱镜,join 正在敲门。答案已更新。顺便说一句,如果您在问题中添加表的架构会更好,更容易。
    • 我仍然有这个新错误db error: ERROR: column reference \"author_id\" is ambiguous。你觉得问题出在哪里?
    • 请把您的查询和表格结构发给我
    【解决方案2】:

    我已经使用以下方法做到了:

    const { PrismaClient } = require('@prisma/client')
    const prisma = new PrismaClient()
    
    const execute = async () => {
      const tr = await prisma.financialTransaction.create({
        data: {
          debit: 150,
          credit: 0,
          financialType: 'payment',
          paymentId: 2,
          author: {
            create: {
              name: 'John Doe',
            }
          }
        },
        include: {
          author: true
        }
      })
      await prisma.financialTransaction.create({
        data: {
          debit: 0,
          credit: 50,
          financialType: 'payment',
          paymentId: 2,
          author: {
            connect: {
              id: tr.author.id
            }
          }
        }
      })
    
      console.log(JSON.stringify(await prisma.financialTransaction.findMany({ include: { author: true } }), null, 2));
    
      const groupTransactions = await prisma.financialTransaction.groupBy({
        by: ['financialType', 'paymentId', 'authorId'],
        _sum: {
          credit: true,
          debit: true,
        },
      })
    
      console.log(groupTransactions);
    };
    
    execute();
    

    使用此架构

    datasource mysql {
      provider = "mysql"
      url      = env("DATABASE_URL")
    }
    
    generator client {
      provider = "prisma-client-js"
    }
    
    model FinancialTransaction {
      id            Int    @id @default(autoincrement())
      debit         Int
      credit        Int
      financialType String
      paymentId     Int
      author        Author @relation(fields: [authorId], references: [id])
      authorId      Int
    }
    
    model Author {
      id           Int                    @id @default(autoincrement())
      name         String
      transactions FinancialTransaction[] @relation
    }
    

    这里是输出

    【讨论】:

    • 你为什么要创建数据,我只想获取而不是插入
    • 这是一个例子:)
    猜你喜欢
    • 2017-01-07
    • 2016-08-23
    • 2021-11-18
    • 2016-03-08
    • 2021-10-30
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多