美文网首页prisma
Prisma js 查询随机结果

Prisma js 查询随机结果

作者: 思考蛙 | 来源:发表于2022-12-05 20:07 被阅读0次

    原生SQL 方案

    prisma.users.findMany({
        orderBy: raw`random()`,
        take: 10
    });
    

    随机field方案

    async handle(req: Request, res: Response) {
            const randomPick = (values: string[]) => {
                const index = Math.floor(Math.random() * values.length);
                return values[index];
            }
            const itemCount = await prismaClient.book.count();
    
            const randomNumber = (min: number, max: number) => {
                return Math.floor(Math.random() * (max - min + 1)) + min;
            }
    
            const orderBy = randomPick(['book_id', 'book_name', 'book_uuid', `book_synopsis`, `book_date_updated`, `book_date_created`]);
            const orderDir = randomPick([`asc`, `desc`]);
    
            let result = await prismaClient.book.findMany({
                orderBy: { [orderBy]: orderDir },
                take: 1,
                skip: randomNumber(0, itemCount - 1),
                select: {
                    book_id: true,
                    book_name: true,
                    book_synopsis: true,
                }
            })
    
            res.send(result)
      }
    

    相关文章

      网友评论

        本文标题:Prisma js 查询随机结果

        本文链接:https://www.haomeiwen.com/subject/emovfdtx.html