* Sort the query results by one or more columns * * @param callback - A function that receives table references and returns the field to sort by * @param direction - Sort direction: 'asc' for ascending, 'desc' for descending (defaults to 'asc') * @returns A QueryBuilder with the ordering
(
callback: OrderByCallback<TContext>,
options: OrderByDirection | OrderByOptions = `asc`,
)
| 627 | * ``` |
| 628 | */ |
| 629 | orderBy( |
| 630 | callback: OrderByCallback<TContext>, |
| 631 | options: OrderByDirection | OrderByOptions = `asc`, |
| 632 | ): QueryBuilder<TContext> { |
| 633 | const aliases = this._getCurrentAliases() |
| 634 | // Add $selected namespace if SELECT clause exists (either regular or functional) |
| 635 | const refProxy = ( |
| 636 | this.query.select || this.query.fnSelect |
| 637 | ? createRefProxyWithSelected(aliases) |
| 638 | : createRefProxy(aliases) |
| 639 | ) as RefsForContext<TContext> |
| 640 | const result = callback(refProxy) |
| 641 | |
| 642 | const opts: CompareOptions = |
| 643 | typeof options === `string` |
| 644 | ? { direction: options, nulls: `first` } |
| 645 | : { |
| 646 | direction: options.direction ?? `asc`, |
| 647 | nulls: options.nulls ?? `first`, |
| 648 | stringSort: options.stringSort, |
| 649 | locale: |
| 650 | options.stringSort === `locale` ? options.locale : undefined, |
| 651 | localeOptions: |
| 652 | options.stringSort === `locale` |
| 653 | ? options.localeOptions |
| 654 | : undefined, |
| 655 | } |
| 656 | |
| 657 | const makeOrderByClause = (res: any) => { |
| 658 | return { |
| 659 | expression: toExpression(res), |
| 660 | compareOptions: opts, |
| 661 | } |
| 662 | } |
| 663 | |
| 664 | // Create the new OrderBy structure with expression and direction |
| 665 | const orderByClauses = Array.isArray(result) |
| 666 | ? result.map((r) => makeOrderByClause(r)) |
| 667 | : [makeOrderByClause(result)] |
| 668 | |
| 669 | const existingOrderBy: OrderBy = this.query.orderBy || [] |
| 670 | |
| 671 | return new BaseQueryBuilder({ |
| 672 | ...this.query, |
| 673 | orderBy: [...existingOrderBy, ...orderByClauses], |
| 674 | }) as any |
| 675 | } |
| 676 | |
| 677 | /** |
| 678 | * Group rows by one or more columns for aggregation |