简体   繁体   中英

how to count records in prisma io?

I am executing a query but the result of the account adds the letter "n", I don't understand why when I execute the query in mysql console it shows it correctly.

const client = await prisma.$queryRaw`SELECT idClient, COUNT(*) as totalCount FROM sales GROUP BY idClient`;
console.log(client)

在此处输入图像描述

executing the same query but in heidiSQL. 在此处输入图像描述

Numbers with an n postfix denote the BigInt type in JavaScript MDN . This is probably due to some queryRaw changes that were made in v4.0.0. The Integer results are now being returned as BigInt. You must change your code to handle the new type . See this section of the upgrade guide.

Example: Given this Schema file

model Customers {
  id  Int  @id @default(autoincrement())
  customerName String
  country String
}

and this script file

async function main() {

  await prisma.customers.createMany({
    data: [
      {
        country: 'USA',
        customerName: 'John Doe',
      },
      {
        country: 'Germany',
        customerName: 'Jane Doe',
      },
      {
        country: 'Canada',
        customerName: 'Adams Doe',
      },
    ],
  });

  const clients = await prisma.customers.groupBy({
    by: ['country'],
    _count: true,
  });
  console.log("Using normal client query with groupBy ")
  console.log(clients);

  const clientsWithRawQuery =
    await prisma.$queryRaw`SELECT Country, COUNT(country) as totalCount
FROM Customers GROUP BY Country`;
  console.log("\n Using queryRaw")
  console.log(clientsWithRawQuery);

  console.log(
    'Before Conversion: Typeof Count:',
    typeof clientsWithRawQuery[0].totalCount
  );

  clientsWithRawQuery.forEach((countryObject) => {
    countryObject.totalCount = Number(countryObject.totalCount);
  });

  console.log(
    'After Conversion: Typeof Count:',
    typeof clientsWithRawQuery[0].totalCount
  );
  console.log('\n', clientsWithRawQuery)
}

The output is

Using normal client query with groupBy 
[
  { _count: 2, country: 'Canada' },
  { _count: 2, country: 'Germany' },
  { _count: 2, country: 'USA' }
]

 Using queryRaw
[
  { Country: 'Canada', totalCount: 2n },
  { Country: 'Germany', totalCount: 2n },
  { Country: 'USA', totalCount: 2n }
]
Before Conversion: Typeof Count: bigint
After Conversion: Typeof Count: number

 [
  { Country: 'Canada', totalCount: 2 },
  { Country: 'Germany', totalCount: 2 },
  { Country: 'USA', totalCount: 2 }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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