Skip to content

Commit

Permalink
feat(model_query_builder): add orderByRandom
Browse files Browse the repository at this point in the history
  • Loading branch information
RomainLanz committed Mar 14, 2024
1 parent 008ec0e commit 659e85b
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/orm/query_builder/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down

0 comments on commit 659e85b

Please sign in to comment.