|
1 | | -import { invariant, isPlainObject } from '@zenstackhq/common-helpers'; |
| 1 | +import { enumerate, invariant, isPlainObject } from '@zenstackhq/common-helpers'; |
2 | 2 | import type { Expression, ExpressionBuilder, ExpressionWrapper, SqlBool, ValueNode } from 'kysely'; |
3 | 3 | import { expressionBuilder, sql, type SelectQueryBuilder } from 'kysely'; |
4 | 4 | import { match, P } from 'ts-pattern'; |
5 | 5 | import type { BuiltinType, DataSourceProviderType, FieldDef, GetModels, ModelDef, SchemaDef } from '../../../schema'; |
6 | | -import { enumerate } from '../../../utils/enumerate'; |
7 | 6 | import type { OrArray } from '../../../utils/type-utils'; |
8 | 7 | import { AGGREGATE_OPERATORS, DELEGATE_JOINED_FIELD_PREFIX, LOGICAL_COMBINATORS } from '../../constants'; |
9 | 8 | import type { |
@@ -755,7 +754,7 @@ export abstract class BaseCrudDialect<Schema extends SchemaDef> { |
755 | 754 | : this.fieldRef(model, field, modelAlias); |
756 | 755 | }; |
757 | 756 |
|
758 | | - enumerate(orderBy).forEach((orderBy) => { |
| 757 | + enumerate(orderBy).forEach((orderBy, index) => { |
759 | 758 | for (const [field, value] of Object.entries<any>(orderBy)) { |
760 | 759 | if (!value) { |
761 | 760 | continue; |
@@ -841,15 +840,16 @@ export abstract class BaseCrudDialect<Schema extends SchemaDef> { |
841 | 840 | } |
842 | 841 | } else { |
843 | 842 | // order by to-one relation |
844 | | - result = result.leftJoin(relationModel, (join) => { |
845 | | - const joinPairs = buildJoinPairs(this.schema, model, modelAlias, field, relationModel); |
| 843 | + const joinAlias = `${modelAlias}$orderBy$${index}`; |
| 844 | + result = result.leftJoin(`${relationModel} as ${joinAlias}`, (join) => { |
| 845 | + const joinPairs = buildJoinPairs(this.schema, model, modelAlias, field, joinAlias); |
846 | 846 | return join.on((eb) => |
847 | 847 | this.and( |
848 | 848 | ...joinPairs.map(([left, right]) => eb(this.eb.ref(left), '=', this.eb.ref(right))), |
849 | 849 | ), |
850 | 850 | ); |
851 | 851 | }); |
852 | | - result = this.buildOrderBy(result, fieldDef.type, relationModel, value, negated); |
| 852 | + result = this.buildOrderBy(result, relationModel, joinAlias, value, negated); |
853 | 853 | } |
854 | 854 | } |
855 | 855 | } |
|
0 commit comments