Skip to content

Commit

Permalink
Fix count helper function for self-referencing relations (#22297)
Browse files Browse the repository at this point in the history
Co-authored-by: Pascal Jufer <pascal-jufer@bluewin.ch>
  • Loading branch information
hanneskuettner and paescuj committed Apr 24, 2024
1 parent 6a38fb4 commit bc3f698
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/chilly-papayas-drive.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@directus/api': patch
---

Fixed count() function filter for self referencing relations
8 changes: 5 additions & 3 deletions api/src/database/helpers/fn/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Query, SchemaOverview } from '@directus/types';
import type { Knex } from 'knex';
import { applyFilter } from '../../../utils/apply-query.js';
import { applyFilter, generateAlias } from '../../../utils/apply-query.js';
import { DatabaseHelper } from '../types.js';

export type FnHelperOptions = {
Expand Down Expand Up @@ -41,10 +41,12 @@ export abstract class FnHelper extends DatabaseHelper {
throw new Error(`Field ${collectionName}.${column} isn't a nested relational collection`);
}

const alias = generateAlias();

let countQuery = this.knex
.count('*')
.from(relation.collection)
.where(relation.field, '=', this.knex.raw(`??.??`, [table, currentPrimary]));
.from({ [alias]: relation.collection })
.where(this.knex.raw(`??.??`, [alias, relation.field]), '=', this.knex.raw(`??.??`, [table, currentPrimary]));

if (options?.query?.filter) {
countQuery = applyFilter(this.knex, this.schema, countQuery, options.query.filter, relation.collection, {}).query;
Expand Down
3 changes: 1 addition & 2 deletions api/src/database/run-ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ import { clone, cloneDeep, isNil, merge, pick, uniq } from 'lodash-es';
import { PayloadService } from '../services/payload.js';
import type { AST, FieldNode, FunctionFieldNode, M2ONode, NestedCollectionNode } from '../types/ast.js';
import { applyFunctionToColumnName } from '../utils/apply-function-to-column-name.js';
import type { ColumnSortRecord } from '../utils/apply-query.js';
import applyQuery, { applyLimit, applySort, generateAlias } from '../utils/apply-query.js';
import applyQuery, { applyLimit, applySort, generateAlias, type ColumnSortRecord } from '../utils/apply-query.js';
import { getCollectionFromAlias } from '../utils/get-collection-from-alias.js';
import type { AliasMap } from '../utils/get-column-path.js';
import { getColumn } from '../utils/get-column.js';
Expand Down

0 comments on commit bc3f698

Please sign in to comment.