简体   繁体   English

使用 Prisma 获取唯一的嵌套值

[英]Get unique nested value with Prisma

I have a relationship that looks like this:我有一个看起来像这样的关系:

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[]
}

A battle has multiple fighters and there is a Vote model which count the vote for each fighter in a battle.一场战斗有多个战士,有一个投票 model 计算战斗中每个战士的投票。 I want to retrieve a battle, include the fighters and include the vote for each fighter.我想检索一场战斗,包括战士并包括每个战士的投票。 I made this query:我做了这个查询:

prisma.battle.findMany({
  take: count,
  skip: skip,
  include: {
    fighters: {
      include: {
        votes: {
          select: {
            count: true
          }
        }
      }
    }
  }
});

Which solves approximately my issue because in the result a fighter has an array of votes, like this:这大约解决了我的问题,因为结果是一个战士有一系列的选票,如下所示:

{
    "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
                }
            ]
        }
    ]
}

But what I would like is, for the best but I doubt it's possible:但我想要的是最好的,但我怀疑这是可能的:

{
  "id": 6,
  "name": "1 hero",
  "image": null,
  "votes":  1
}

To have the count of votes directly in my fighter object or at least, only one vote in the fighter object直接在我的战斗机 object 中计票,或者至少,在战斗机 object 中只有一票

{
  "id": 6,
  "name": "1 hero",
  "image": null,
  "votes": {
     "count": 1
  }
}

I don't know if my issue is a schema problem between my models or if I can solve it with the Prisma queries.我不知道我的问题是否是我的模型之间的模式问题,或者我是否可以使用 Prisma 查询来解决它。 I tried to use the include and select API from Prisma but I couldn't solve this.我尝试使用来自 Prisma 的includeselect API 但我无法解决这个问题。 Does anyone have an idea about this?有人对此有想法吗?

You could use _count clause which would allow you to have response similar to what you are expecting.您可以使用 _count 子句,这将使您得到与您期望的类似的响应。

Here's the query:这是查询:

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();
  });

Here's the sample response:这是示例响应:

[
  {
    "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
        }
      }
    ]
  }
]

Reference for using _count clause: _count prisma _count子句的使用参考: _count prisma

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM