使用 Prisma 获取唯一的嵌套值

Get unique nested value with Prisma

我的关系是这样的:

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 的 includeselect API 但我无法解决这个问题。有人对此有想法吗?

您可以使用 _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