fix: filter with appends (#1819)

This commit is contained in:
ChengLei Shao 2023-05-08 11:18:42 +08:00 committed by GitHub
parent c8c081eba5
commit 2c29daedb5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 101 additions and 1 deletions

View File

@ -88,6 +88,97 @@ describe('find with associations', () => {
expect(results[0].get('name')).toEqual('u1');
});
it('should filter with append', async () => {
const Post = db.collection({
name: 'posts',
fields: [
{ name: 'title', type: 'string' },
{
name: 'user',
type: 'belongsTo',
},
{
name: 'category',
type: 'belongsTo',
},
],
});
const Category = db.collection({
name: 'categories',
fields: [
{
name: 'name',
type: 'string',
},
],
});
const User = db.collection({
name: 'users',
fields: [
{ name: 'name', type: 'string' },
{ type: 'belongsTo', name: 'organization' },
{
type: 'belongsTo',
name: 'department',
},
],
});
const Org = db.collection({
name: 'organizations',
fields: [{ name: 'name', type: 'string' }],
});
const Dept = db.collection({
name: 'departments',
fields: [{ name: 'name', type: 'string' }],
});
await db.sync();
await Post.repository.create({
values: [
{
title: 'p1',
category: { name: 'c1' },
user: {
name: 'u1',
organization: {
name: 'o1',
},
department: {
name: 'd1',
},
},
},
{
title: 'p2',
category: { name: 'c2' },
user: {
name: 'u2',
organization: {
name: 'o2',
},
department: {
name: 'd2',
},
},
},
],
});
const filterResult = await Post.repository.find({
appends: ['user.department'],
filter: {
'user.name': 'u1',
},
});
expect(filterResult[0].user.department).toBeDefined();
});
it('should filter by association field', async () => {
const User = db.collection({
name: 'users',

View File

@ -307,6 +307,13 @@ export class OptionsParser {
attributes,
};
} else {
const existInclude = queryParams['include'][existIncludeIndex];
if (existInclude.attributes && Array.isArray(existInclude.attributes) && existInclude.attributes.length == 0) {
existInclude.attributes = {
include: [],
};
}
setInclude(
model.associations[queryParams['include'][existIncludeIndex].association].target,
queryParams['include'][existIncludeIndex],

View File

@ -278,6 +278,7 @@ export class Repository<TModelAttributes extends {} = any, TCreationAttributes e
// @ts-ignore
const primaryKeyField = model.primaryKeyField || model.primaryKeyAttribute;
// find all ids
const ids = (
await model.findAll({
...opts,
@ -299,6 +300,7 @@ export class Repository<TModelAttributes extends {} = any, TCreationAttributes e
return [];
}
// find template model
const templateModel = await model.findOne({
...opts,
includeIgnoreAttributes: false,
@ -318,7 +320,7 @@ export class Repository<TModelAttributes extends {} = any, TCreationAttributes e
rows = await handleAppendsQuery({
queryPromises: opts.include.map((include) => {
const options = {
...omit(opts, ['limit', 'offset']),
...omit(opts, ['limit', 'offset', 'filter']),
include: include,
where,
transaction,