How can I include nested relation for all potential layers in Loopback 4?

282 Views Asked by At

I'm trying to make a REST API where all the employees in the company are returned in a hierarchical order(Employees that don't have a manager are at the base tree while the people they manage are right under them, and so on.

I'm including the employees[] relation and an identical nested relation in the filter while calling the data from the repository. Currently, the call for employees only happens on the first two layers, and the employees[] relation isn't shown on the third layer so there is no way to see the layers after that.

Here is the part of the code that calls the relations for the first two layers:

filter = {
        include: [
          {
            relation: 'employees',
            scope: {
              include: [{relation: 'employees'}],
            },
          },
        ],
        where: {managerId: -1},
      };

Is there a way declare this filter so it scales into all layers my hierarchy might have? Or do I have to add as many new scopes as I think I need?

1

There are 1 best solutions below

0
On

You might not be able to achieve this in a single filter clause. Better fetch underlying employees recursively for each layer.

EDIT Actually, we can indeed do the recursion in the filter clause itself if we know how many max layers there can be. It will also break the recursion when there are no more child layers. Then your filter clause would look like

let filter = {
  include: {
    relation: 'employees'
  },
  where: {managerId: -1},
};

let childLayer = {
  relation : 'employees'
};

let previousLayer = filter.include;
for(let i=0; i<=10; i++){  //do this for 10 layers
  previousLayer.scope = {
    include : JSON.parse(JSON.stringify(childLayer))  //to avoid reference carry forwards
  };
  previousLayer = previousLayer.scope.include;
}

//do the query here using filter object