diff --git a/packages/database/src/__tests__/repository.test.ts b/packages/database/src/__tests__/repository.test.ts index 0b67078a6..1f1c0bb67 100644 --- a/packages/database/src/__tests__/repository.test.ts +++ b/packages/database/src/__tests__/repository.test.ts @@ -97,6 +97,34 @@ describe('repository.find', () => { await db.close(); }); + test('find pk with filter', async () => { + const Test = db.collection({ + name: 'tests', + fields: [ + { type: 'string', name: 'name' }, + { type: 'string', name: 'status' }, + ], + }); + + await db.sync(); + + const t1 = await Test.repository.create({ + values: { + name: 't1', + status: 'draft', + }, + }); + + const result = await Test.repository.findOne({ + filterByPk: t1.get('id'), + filter: { + status: 'published', + }, + }); + + expect(result).toBeNull(); + }); + it('findOne', async () => { const data = await User.repository.findOne({ filter: { diff --git a/packages/database/src/options-parser.ts b/packages/database/src/options-parser.ts index e0027171a..1e4538156 100644 --- a/packages/database/src/options-parser.ts +++ b/packages/database/src/options-parser.ts @@ -1,6 +1,6 @@ import { Appends, Except, FindOptions } from './repository'; import FilterParser from './filter-parser'; -import { FindAttributeOptions, ModelCtor } from 'sequelize'; +import { FindAttributeOptions, ModelCtor, Op } from 'sequelize'; import { Database } from './database'; const debug = require('debug')('noco-database'); @@ -39,8 +39,20 @@ export class OptionsParser { } toSequelizeParams() { - const filterParams = this.options?.filterByPk ? this.parseFilterByPk() : this.filterParser.toSequelizeParams(); - return this.parseSort(this.parseFields(filterParams)); + const queryParams = this.filterParser.toSequelizeParams(); + + if (this.options?.filterByPk) { + queryParams.where = { + [Op.and]: [ + queryParams.where, + { + [this.model.primaryKeyAttribute]: this.options.filterByPk, + }, + ], + }; + } + + return this.parseSort(this.parseFields(queryParams)); } /**