5

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?

derfred
  • 18,881
  • 3
  • 23
  • 25
  • I'm doing relatively the same thing in Strapi v3, and now I'm curious... does it not work in v4? What's so drastically different in v4? – Kalnode Jun 23 '22 at 00:38
  • @MarsAndBack It's been a while so I can't tell you what the problem was any more. But if you are having problems, check out my answer below – derfred Jun 23 '22 at 13:18

1 Answers1

0

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 })
derfred
  • 18,881
  • 3
  • 23
  • 25