Laf*_*une 6 database postgresql prisma
我有一个名为的表financial_transaction,其中包含如下数据:
| ID | 借方 | 信用 | 财务类型 | 付款ID | 支付 | 作者id | 作者 |
|---|---|---|---|---|---|---|---|
| 1 | 150 | 0 | 支付 | 2 | - | 1 | - |
| 2 | 0 | 50 | 支付 | 2 | - | 1 | - |
所以我从这些数据中得到的愿望是:
payment_id。author.debits和相加credits。financial_type字段 payment_id。这就是我想要的:
[
{
payment_id: 2,
author: {
first_name: John,
last_name: Doe
}
debit: 150,
credit: 50,
financial_type: Payment
}
]
Run Code Online (Sandbox Code Playgroud)
这也是我的 Prisma Scehma:
enum FinancialType {
Payment
Expense
Withdraw
}
Run Code Online (Sandbox Code Playgroud)
用户表
model User {
id Int @id @default(autoincrement())
first_name String
last_name String
saved_payments Payment[]
saved_financial_transactions FinancialTransaction[]
}
Run Code Online (Sandbox Code Playgroud)
付款表
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?
}
Run Code Online (Sandbox Code Playgroud)
财务交易表
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?
}
Run Code Online (Sandbox Code Playgroud)
我尝试用棱镜来实现这一点,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;`;
Run Code Online (Sandbox Code Playgroud)
但这不起作用......所以我的问题是有没有一种方法 Prisma 可以做到这一点并给我这个?
使用本机查询。
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;
Run Code Online (Sandbox Code Playgroud)