feat(database): support find with filter and where (#3097)

This commit is contained in:
ChengLei Shao 2023-11-26 21:41:40 +08:00 committed by GitHub
parent d574c8c7ce
commit c7ef9618a9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 46 additions and 5 deletions

View File

@ -119,6 +119,7 @@ describe('repository.find', () => {
const tags = await Tag.repository.create({
values: [{ name: 't1' }, { name: 't2' }],
});
await User.repository.createMany({
records: [
{
@ -188,6 +189,39 @@ describe('repository.find', () => {
await db.close();
});
it('should find with filter', async () => {
const users = await User.repository.find({
filter: {
name: 'user1',
},
});
expect(users.length).toBe(1);
});
it('should find with where', async () => {
const users = await User.repository.find({
where: {
name: 'user1',
},
});
expect(users.length).toBe(1);
});
it('should find with filter and where', async () => {
const users = await User.repository.find({
filter: {
name: 'user1',
},
where: {
name: 'user2',
},
});
expect(users.length).toBe(0);
});
it('should appends with belongs to association', async () => {
const posts = await Post.repository.find({
appends: ['user'],

View File

@ -3,16 +3,16 @@ import lodash from 'lodash';
import {
Association,
BulkCreateOptions,
ModelStatic,
Op,
Sequelize,
FindAndCountOptions as SequelizeAndCountOptions,
CountOptions as SequelizeCountOptions,
CreateOptions as SequelizeCreateOptions,
DestroyOptions as SequelizeDestroyOptions,
FindAndCountOptions as SequelizeAndCountOptions,
FindOptions as SequelizeFindOptions,
UpdateOptions as SequelizeUpdateOptions,
ModelStatic,
Op,
Sequelize,
Transactionable,
UpdateOptions as SequelizeUpdateOptions,
WhereOperators,
} from 'sequelize';
import { Collection } from './collection';
@ -778,6 +778,13 @@ export class Repository<TModelAttributes extends {} = any, TCreationAttributes e
const params = parser.toSequelizeParams();
debug('sequelize query params %o', params);
if (options.where && params.where) {
params.where = {
[Op.and]: [params.where, options.where],
};
}
return { where: {}, ...options, ...params };
}