feat: sortBy through table value (#209)

This commit is contained in:
ChengLei Shao 2022-02-27 23:02:26 +08:00 committed by GitHub
parent 344057ccee
commit 1db71b166d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 68 additions and 6 deletions

View File

@ -1,5 +1,5 @@
import { mockDatabase } from '@nocobase/test'; import { mockDatabase } from '@nocobase/test';
import { Database } from '../../index'; import { BelongsToManyRepository, Database } from '../../index';
describe('associated field order', () => { describe('associated field order', () => {
let db: Database; let db: Database;
@ -63,6 +63,12 @@ describe('associated field order', () => {
name: 'tags', name: 'tags',
sortBy: 'name', sortBy: 'name',
}, },
{
type: 'belongsToMany',
name: 'images',
through: 'posts_images',
sortBy: ['-posts_images.sort'],
},
], ],
}); });
@ -76,6 +82,27 @@ describe('associated field order', () => {
}, },
], ],
}); });
db.collection({
name: 'posts_images',
fields: [{ type: 'integer', name: 'sort' }],
});
db.collection({
name: 'images',
fields: [
{
type: 'belongsToMany',
name: 'posts',
through: 'posts_images',
},
{
type: 'string',
name: 'url',
},
],
});
await db.sync(); await db.sync();
}); });
@ -157,4 +184,37 @@ describe('associated field order', () => {
expect(u1Records[0].count).toBeUndefined(); expect(u1Records[0].count).toBeUndefined();
expect(u1Records.map((p) => p['name'])).toEqual(['a', 'b', 'c']); expect(u1Records.map((p) => p['name'])).toEqual(['a', 'b', 'c']);
}); });
it('should sortBy through table field', async () => {
const p1 = await db.getRepository('posts').create({
values: {
name: 'u1',
},
});
const t1 = await db.getRepository('images').create({
values: {
url: 't1',
},
});
const t2 = await db.getRepository('images').create({
values: {
url: 't2',
},
});
const postImageRepository = db.getRepository<BelongsToManyRepository>('posts.images', p1.get('id') as string);
await postImageRepository.add([[t2.get('id') as string, { sort: 2 }]]);
await postImageRepository.add([[t1.get('id') as string, { sort: 1 }]]);
const p1Result = await db.getRepository('posts').findOne({
appends: ['images'],
});
const p1JSON = p1Result.toJSON();
const p1Images = p1JSON['images'];
expect(p1Images.map((i) => i['url'])).toEqual(['t2', 't1']);
});
}); });

View File

@ -101,12 +101,14 @@ export class Model<TModelAttributes extends {} = any, TCreationAttributes extend
sortBy = [sortBy]; sortBy = [sortBy];
} }
const orders = sortBy.map((sortItem) => { const orderItems = [];
const direction = sortItem.startsWith('-') ? 'desc' : 'asc'; const orderDirections = [];
sortItem.replace('-', '');
return [sortItem, direction]; sortBy.forEach((sortItem) => {
orderDirections.push(sortItem.startsWith('-') ? 'desc' : 'asc');
orderItems.push(sortItem.replace('-', ''));
}); });
return lodash.sortBy(data, ...orders); return lodash.orderBy(data, orderItems, orderDirections);
} }
} }