fix: tree with fields option (#1833)

This commit is contained in:
ChengLei Shao 2023-05-10 16:32:36 +08:00 committed by GitHub
parent fab448c486
commit ecd7540f7a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 62 additions and 8 deletions

View File

@ -16,6 +16,57 @@ describe('tree test', function () {
await db.close();
});
it('should works with appends option', async () => {
const collection = db.collection({
name: 'categories',
tree: 'adjacency-list',
fields: [
{ type: 'string', name: 'name' },
{
type: 'belongsTo',
name: 'parent',
treeParent: true,
},
{
type: 'hasMany',
name: 'children',
treeChildren: true,
},
],
});
await db.sync();
await collection.repository.create({
values: [
{
name: 'c1',
children: [
{
name: 'c11',
},
{
name: 'c12',
},
],
},
{
name: 'c2',
},
],
});
const tree = await collection.repository.find({
tree: true,
filter: {
parentId: null,
},
fields: ['name'],
});
expect(tree.length).toBe(2);
});
it('should not return children property when child nodes are empty', async () => {
const collection = db.collection({
name: 'categories',
@ -60,6 +111,7 @@ describe('tree test', function () {
filter: {
parentId: null,
},
tree: true,
});
const c2 = tree.find((item) => item.name === 'c2');

View File

@ -10,20 +10,22 @@ export class AdjacencyListRepository extends Repository {
}
async find(options: FindOptions & { addIndex?: boolean } = {}): Promise<any> {
const parentNodes = await super.find(lodash.omit(options));
if (options.raw) {
return parentNodes;
if (options.raw || !options.tree) {
return await super.find(options);
}
const collection = this.collection;
const primaryKey = collection.model.primaryKeyAttribute;
if (options.fields && !options.fields.includes(primaryKey)) {
options.fields.push(primaryKey);
}
const parentNodes = await super.find(options);
if (parentNodes.length === 0) {
return [];
}
const templateModel = parentNodes[0];
const collection = this.collection;
const primaryKey = collection.model.primaryKeyAttribute;
const { treeParentField } = collection;
const foreignKey = treeParentField.options.foreignKey;