Getting random records from strapi v4 entity service

Viewed 403

In Strapi v3 the following code would return random records:

strapi.query(table).model.query(qb => {
  qb.limit(count); //with limit
  qb.orderByRaw("RAND()") //with rand
}).fetchAll()

How can I achieve the same in v4?

1 Answers

For reference here is how I solved this:

const qb = strapi.db.entityManager
  .createQueryBuilder("table")
  .init({ select: ["id"] })
  .getKnexQuery()
  .orderByRaw(randomSort())

const ids = (await qb).map(r => r.id)
const filters = { id: { $in: ids } }
return await strapi.entityService.findMany(table, { filters })
Related