我有一個看起來像這樣的關系:
model Fighter {
id Int @id @default(autoincrement())
name String
image String?
description String?
battles Battle[]
votes Vote[]
}
model Vote {
Fighter Fighter @relation(fields: [fighterId], references: [id])
fighterId Int
Battle Battle @relation(fields: [battleId], references: [id])
battleId Int
count Int @default(0)
@@id([fighterId, battleId])
}
model Battle {
id Int @id @default(autoincrement())
slug String @unique
name String
fighters Fighter[]
votes Vote[]
}
一場戰斗有多個戰士,并且有一個投票模型可以計算戰斗中每個戰士的投票。我想檢索一場戰斗,包括戰士并包括每個戰士的投票。我做了這個查詢:
prisma.battle.findMany({
take: count,
skip: skip,
include: {
fighters: {
include: {
votes: {
select: {
count: true
}
}
}
}
}
});
這大致解決了我的問題,因為結果戰斗機有一系列選票,如下所示:
{
"id": 2,
"slug": "Random-1",
"name": "Random 1",
"fighters": [
{
"id": 3,
"name": "1 dragon",
"image": null,
"votes": [
{
"count": 3
}
]
},
{
"id": 6,
"name": "1 hero",
"image": null,
"votes": [
{
"count": 1
}
]
}
]
}
但我想要的是,最好但我懷疑這是可能的:
{
"id": 6,
"name": "1 hero",
"image": null,
"votes": 1
}
直接在我的戰斗機物件中計算選票,或者至少在戰斗機物件中只有一票
{
"id": 6,
"name": "1 hero",
"image": null,
"votes": {
"count": 1
}
}
我不知道我的問題是我的模型之間的架構問題,還是我可以使用 Prisma 查詢解決它。我嘗試使用 Prisma 的includeand selectAPI,但我無法解決這個問題。有人對此有任何想法嗎?
uj5u.com熱心網友回復:
您可以使用 _count 子句,它可以讓您獲得類似于您所期望的回應。
這是查詢:
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
async function main() {
await prisma.battle.create({
data: {
name: 'Battle of the Vowels',
slug: 'battle-of-the-vowels',
fighters: {
create: {
name: 'Kabal',
description:
'Kabal is a fictional character in the Star Wars franchise. He is a member of the Jedi Order.',
image:
'https://vignette.wikia.nocookie.net/starwars/images/7/7e/Kabal_HS-SWE.png/revision/latest?cb=20170504075154',
votes: {
create: {
battleId: 1,
},
},
},
},
},
});
//
// Updated Query
//
const battle = await prisma.battle.findMany({
// take: count,
// skip: skip,
include: {
fighters: {
include: {
_count: {
select: {
votes: true,
},
},
},
},
},
});
console.log(JSON.stringify(battle, null, 2));
}
main()
.catch((e) => {
throw e;
})
.finally(async () => {
await prisma.$disconnect();
});
這是示例回應:
[
{
"id": 1,
"slug": "battle-of-the-vowels",
"name": "Battle of the Vowels",
"fighters": [
{
"id": 1,
"name": "Kabal",
"image": "https://vignette.wikia.nocookie.net/starwars/images/7/7e/Kabal_HS-SWE.png/revision/latest?cb=20170504075154",
"description": "Kabal is a fictional character in the Star Wars franchise. He is a member of the Jedi Order.",
"_count": {
"votes": 1
}
}
]
}
]
使用 _count 子句的參考:_count prisma
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/463286.html
標籤:javascript 数据库 棱镜
