From 659e85b6af9680cb127478f28c310d819dfbfa8f Mon Sep 17 00:00:00 2001 From: Romain Lanz Date: Thu, 14 Mar 2024 18:32:01 +0100 Subject: [PATCH] feat(model_query_builder): add orderByRandom --- src/orm/query_builder/index.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/orm/query_builder/index.ts b/src/orm/query_builder/index.ts index 5be3cca1..096a4165 100644 --- a/src/orm/query_builder/index.ts +++ b/src/orm/query_builder/index.ts @@ -643,6 +643,27 @@ export class ModelQueryBuilder return this.addWhereHas(relationName, 'not', operator, value) } + /** + * Order results by random value. + */ + orderByRandom(seed = '') { + switch (this.client.dialect.name) { + case 'sqlite3': + case 'better-sqlite3': + case 'postgres': + case 'redshift': + return this.orderByRaw('RANDOM()') + case 'mysql': + return this.orderByRaw(`RAND(${seed})`) + case 'mssql': + return this.orderByRaw('NEWID()') + case 'oracledb': + return this.orderByRaw('dbms_random.value') + default: + throw new Error(`Cannot order by random for the given dialect ${this.client.dialect.name}`) + } + } + /** * Define a relationship to be preloaded */