Get random records from `findMany` and also with pagination
See original GitHub issueProblem
Comming from https://github.com/prisma/prisma/discussions/5886.
As discussed in Prisma 1 forum, looks like there is no way to find random records with findMany
. Indeed, this is such a challenge to use with pagination
.
Suggested solution
Providing a random
function from prisma
would be an easy solution for users therefore we can expect results with orderBy: random()
. Although this results in a bad performance in pure sql
, I think Prisma
can do better internally without just exposing the random inside the sql
.
Alternatives
If the below pagination query and raw query could aggregate, it would scope down many limitations.
prisma.item.findMany({
...relayToPrismaPagination({
after,
before,
first,
last,
}),
where: {
...filters,
},
orderBy: {id: 'desc'},
});
select * from "Item" limit 20
offset floor(random() * (select count(*) from "Item"));
Issue Analytics
- State:
- Created 3 years ago
- Reactions:23
- Comments:6
Top Results From Across the Web
how to create pagination in php with random records but with ...
Try using this.. Form what i understand. consider no of records on a single page must be 'x'. So, mysql_query("select * from primaryinfo...
Read more >MongoDB Pagination, Fast & Consistent | by Mosius - Medium
By using the keyset method, we lose the ability to randomly access the pages. Simply saying, we actually can't get page 3 without...
Read more >Model Querying - Basics - Sequelize
Sequelize provides various methods to assist querying your database for data.
Read more >Query | GORM - GORM
Get last record, ordered by primary key desc ... Find(&user) , the Find method accepts both struct and slice data ... Also check...
Read more >@mswjs/data - npm
Cursor-based pagination. The cursor option of the findMany query expects a primary key value of a model to start the pagination from.
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Yes, we absolutely need this feature. Please, consider adding it into the next upgrades.
@hyochan
My temporary solution is to add a ‘randomizer’ field to your model. When you create your item, you store a random string into that ‘randomizer’. Then in your query you order it by adding orderBy: {randomizer: ‘desc’} for exemple.
I’ve used short-uuid to generate my random string.
Not perfect of course, mainly because even if randomised, the items are always returned in the same order (but I guess its necessary for pagination so…).
Hope this help 😃