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 */