fix: single relation repository appends query issue (#901)

(cherry picked from commit 20c1477015)
This commit is contained in:
ChengLei Shao 2022-10-13 11:15:27 +08:00 committed by chenos
parent 7ca8e562ce
commit d777fede90
3 changed files with 70 additions and 4 deletions

View File

@ -0,0 +1,64 @@
import Database, { BelongsToRepository, Collection, mockDatabase } from '@nocobase/database';
describe('appends', () => {
let db: Database;
let User: Collection;
let Post: Collection;
let A1: Collection;
let A2: Collection;
afterEach(async () => {
await db.close();
});
beforeEach(async () => {
db = mockDatabase();
User = db.collection({
name: 'users',
fields: [
{ type: 'string', name: 'name' },
{ type: 'hasMany', name: 'posts' },
],
});
Post = db.collection({
name: 'posts',
fields: [
{ type: 'string', name: 'title' },
{
type: 'belongsTo',
name: 'user',
},
],
});
await db.sync();
});
it('should find with appends', async () => {
await User.repository.create({
values: {
name: 'u1',
posts: [
{
title: 'p1',
},
],
},
});
const p1 = await Post.repository.findOne({});
const repository = new BelongsToRepository(Post, 'user', p1['id']);
const user = await repository.findOne({
appends: ['posts'],
});
const data = user.toJSON();
expect(data['posts'][0]['title']).toEqual('p1');
});
});

View File

@ -46,6 +46,7 @@ export abstract class SingleRelationRepository extends RelationRepository {
async find(options?: SingleRelationFindOption): Promise<Model<any> | null> {
const transaction = await this.getTransaction(options);
const findOptions = this.buildQueryOptions({
...options,
});
@ -56,6 +57,7 @@ export abstract class SingleRelationRepository extends RelationRepository {
if (findOptions?.include?.length > 0) {
const templateModel = await sourceModel[getAccessor]({
...findOptions,
includeIgnoreAttributes: false,
transaction,
attributes: [this.targetKey()],
group: `${this.targetModel.name}.${this.targetKey()}`,

View File

@ -6,10 +6,6 @@ type HandleAppendsQueryOptions = {
queryPromises: Array<any>;
};
export function md5(value: string) {
return crypto.createHash('md5').update(value).digest('hex');
}
export async function handleAppendsQuery(options: HandleAppendsQueryOptions) {
const { templateModel, queryPromises } = options;
@ -47,3 +43,7 @@ export async function handleAppendsQuery(options: HandleAppendsQueryOptions) {
return rows;
}
export function md5(value: string) {
return crypto.createHash('md5').update(value).digest('hex');
}