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({ const tags = await Tag.repository.create({
values: [{ name: 't1' }, { name: 't2' }], values: [{ name: 't1' }, { name: 't2' }],
}); });
await User.repository.createMany({ await User.repository.createMany({
records: [ records: [
{ {
@ -188,6 +189,39 @@ describe('repository.find', () => {
await db.close(); 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 () => { it('should appends with belongs to association', async () => {
const posts = await Post.repository.find({ const posts = await Post.repository.find({
appends: ['user'], appends: ['user'],

View File

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