diff --git a/packages/backend-core/src/sql/sql.ts b/packages/backend-core/src/sql/sql.ts index ba3076e553..1a7e3beba4 100644 --- a/packages/backend-core/src/sql/sql.ts +++ b/packages/backend-core/src/sql/sql.ts @@ -1604,8 +1604,17 @@ class InternalBuilder { // handle relationships with a CTE for all others if (relationships?.length && aggregations.length === 0) { + const mainTable = this.query.tableAliases?.[table.name] || table.name + const cte = this.addSorting( + this.knex + .with("paginated", query.clone().clearSelect().select("*")) + .select(this.generateSelectStatement()) + .from({ + [mainTable]: "paginated", + }) + ) // add JSON aggregations attached to the CTE - return this.addJsonRelationships(query, table.name, relationships) + return this.addJsonRelationships(cte, table.name, relationships) } return query diff --git a/packages/server/src/api/controllers/row/utils/sqlUtils.ts b/packages/server/src/api/controllers/row/utils/sqlUtils.ts index b6215cc5b6..9f5e14d732 100644 --- a/packages/server/src/api/controllers/row/utils/sqlUtils.ts +++ b/packages/server/src/api/controllers/row/utils/sqlUtils.ts @@ -161,15 +161,14 @@ export async function buildSqlFieldList( let table: Table if (isView) { table = await sdk.views.getTable(source.id) - fields = fields.filter(f => table.schema[f].type !== FieldType.LINK) } else { table = source } if (isView) { - fields = Object.keys(helpers.views.basicFields(source)).map( - c => `${table.name}.${c}` - ) + fields = Object.keys(helpers.views.basicFields(source)) + .filter(f => table.schema[f].type !== FieldType.LINK) + .map(c => `${table.name}.${c}`) } else { fields = extractRealFields(source) }