原生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)
}
网友评论