From 104be20c6016ae2c3ece6da7d5182422bcb2ae46 Mon Sep 17 00:00:00 2001 From: ChengLei Shao Date: Sun, 5 Mar 2023 14:29:40 +0800 Subject: [PATCH] fix: filter by association field with underscored (#1537) * fix: filter by association field with underscored * fix: test --- .../database/src/__tests__/filter.test.ts | 60 +++++++++++++++++++ packages/core/database/src/filter-parser.ts | 2 +- 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 packages/core/database/src/__tests__/filter.test.ts diff --git a/packages/core/database/src/__tests__/filter.test.ts b/packages/core/database/src/__tests__/filter.test.ts new file mode 100644 index 000000000..fddf33f37 --- /dev/null +++ b/packages/core/database/src/__tests__/filter.test.ts @@ -0,0 +1,60 @@ +import Database from '../database'; +import { mockDatabase } from '../mock-database'; + +describe('filter', () => { + let db: Database; + + beforeEach(async () => { + db = mockDatabase(); + + await db.clean({ drop: true }); + }); + + afterEach(async () => { + await db.close(); + }); + + it('should filter by association field', async () => { + const UserCollection = db.collection({ + name: 'users', + fields: [ + { type: 'string', name: 'name' }, + { type: 'hasMany', name: 'posts' }, + ], + }); + + const PostCollection = db.collection({ + name: 'posts', + fields: [ + { type: 'string', name: 'title' }, + { type: 'belongsTo', name: 'user' }, + ], + }); + + await db.sync(); + + const user = await UserCollection.repository.create({ + values: { + name: 'John', + posts: [ + { + title: 'p1', + }, + { + title: 'p2', + }, + ], + }, + }); + + const response = await UserCollection.repository.find({ + filter: { + 'posts.createdAt': { + $dateOn: user.get('createdAt'), + }, + }, + }); + + expect(response).toHaveLength(1); + }); +}); diff --git a/packages/core/database/src/filter-parser.ts b/packages/core/database/src/filter-parser.ts index 65521d526..a1ebfa47c 100644 --- a/packages/core/database/src/filter-parser.ts +++ b/packages/core/database/src/filter-parser.ts @@ -178,7 +178,7 @@ export default class FilterParser { origins.push(attr); // if it is target model attribute if (target.rawAttributes[attr]) { - associationKeys.push(attr); + associationKeys.push(target.rawAttributes[attr].field || attr); target = null; } else if (target.associations[attr]) { // if it is target model association (nested association filter)