Typescript 根据随机数在棱柱形中查找多行

Typescript 根据随机数在棱柱形中查找多行,typescript,express,orm,prisma,Typescript,Express,Orm,Prisma,棱镜2 ORM 你好,我有没有办法把它缩短一点?看起来真的很糟糕。。我试过打圈,但它断了 生成卡片的随机索引 export const getRandomCards = (cards: any) => { let randomCards: number[] = []; while (randomCards.length < 5) { let card = Math.floor(Math.random() * cards.length); if (!random

棱镜2 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;
};

这样做是正确的方法吗?

我建议您在查询中使用
in
操作符

您当前的方法存在的问题是“非常手工”。如果你想查询20张随机卡片呢?你不能写20个案子。。。(记住,开发人员是懒惰的)

const cards=wait prisma.event.findMany({
其中:{
id:{in:randomCards},
},
})
你为什么要这么做

const cards=wait prisma.event.findMany();
如果(!卡片)抛出新错误();
我想你可以跳过它。 如果您有20万条记录,会发生什么?您将查询整个表以。。。是否放弃数据,然后重新运行5个查询

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

此外,我建议您:

  • 通过
    randomCards
    重命名
    randomCards
    ,与
    getRandomCards
    ->
    getRandomCards
    相同(否则,将假定变量持有一个卡片对象,而它只持有ID)
  • event
    实体重命名为
    card
    可能?读起来有点违反直觉:
    const cards=wait prisma.event.XXX
    。它是
    event
    还是
    cards
参考:


非常感谢,伙计!我只需要一个这样的提示,我绝对肯定我做错了。
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();
};