System Information
-
Strapi Version: 4.4.1
-
Operating System: macOS Ventura
-
Database: postgres
-
Node Version: 16.14
-
NPM Version:
-
Yarn Version:
Hi,
I want to get some randoms rows from my table, I didn’t found a solution using strapi services, then I tried to do custom queries but this not possible in V4.
I want to achieve that in a custom resolver.
Someone has a solution to achieve that ?
Thanks in advance.
If you just want to randomly sort results within a request, you can use this plugin:
If you want to take a random sample from the whole collection I’d recommend combining raw SQL query (to tap into the random ordering capabilities of your DB) and the Entity Service (to leverage the Strapi’s handling of relations, components etc.) Something along the lines of:
const uid = "api::<name>.<content-type>";
const ids = (
await strapi.db.connection
.select("id")
.from(strapi.getModel(uid).collectionName)
// The random function of your DB. This one is Postgres'.
.orderByRaw("RANDOM()")
// Your desired number of samples.
.limit(10)
).map(it => it.id)
const samples = await strapi.entityService.findMany(uid, {
filters: {
id: {
$in: ids
}
}
})
Note that this approach doesn’t play well with pagination - you couldn’t avoid duplicate entries across page requests. Doing that is quite more complicated.
The second proposition is exactly what I was looking, thanks !
And of course it works 