根据随机数在 Prisma ORM 中查找许多行

Find many rows in Prisma ORM basing on random numbers

Prisma2 ORM

您好,请问有什么办法可以缩短吗?看起来真的很糟糕。我试过循环,但它坏了。

正在生成卡片的随机索引

export const getRandomCards = (cards: any) => {
  let randomCards: number[] = [];
  while (randomCards.length < 5) {
    let card = Math.floor(Math.random() * cards.length);
    if (!randomCards.includes(card)) randomCards.push(card);
  }
  return randomCards;
};

然后我想根据先前从数组中生成的索引发送卡片。

import express, { Request, Response, NextFunction } from "express";

import { getRandomCards } from "./../../../util";

import prisma from "../../../client";

export const getEvents = async (
  _req: Request,
  res: Response,
  next: NextFunction
) => {
  const cards = await prisma.event.findMany();

  if (!cards) throw new Error();

  const randomCards = getRandomCards(cards);

  try {
    const firstCard = await prisma.event.findUnique({
      where: {
        id: randomCards[0],
      },
    });
    const secondCard = await prisma.event.findUnique({
      where: {
        id: randomCards[1],
      },
    });
    const thirdCard = await prisma.event.findUnique({
      where: {
        id: randomCards[2],
      },
    });
    const fourthCard = await prisma.event.findUnique({
      where: {
        id: randomCards[3],
      },
    });
    const fifthCard = await prisma.event.findUnique({
      where: {
        id: randomCards[4],
      },
    });

    res.send({
      cards: { firstCard, secondCard, thirdCard, fourthCard, fifthCard },
    });
  } catch (err) {
    throw new Error(err);
  }

  next();
};

这样做是正确的做法吗?

我建议您在查询中使用 in 运算符。

您当前方法的问题在于它“非常手动”。如果要查询20张随机卡片怎么办?你不能写 20 个案例...(记住,开发者是懒惰的)

const cards = await prisma.event.findMany({
  where: {
    id: { in: randomCards },
  },
})

为什么需要这样做?

const cards = await prisma.event.findMany();

if (!cards) throw new Error();

我想你可以跳过它。 如果您有 20 万条记录会怎样?您将查询整个 table 只是...丢弃数据,然后重新 运行 5 个查询?

只是 运行 我上面给你的查询,也许你可以做一个检查,比如“if cards.length === 0”,然后抛出一个错误。

此外,我建议您:

  • randomCards 重命名为 randomCardIds,与 getRandomCards -> getRandomCardIds 相同(否则人们会假设该变量包含一个卡片对象,而它只包含 ID。
  • 可以将 event 实体重命名为 card 吗?读起来有点违反直觉: const cards = await prisma.event.XXX 。是 event 还是 cards

参考: