Layered Filter with LoopBack JS

My problem is that I cannot figure out how to get multi-level relationship structures in a single request using LoopBack. I have 3 models: Continent , Country , County . I would like to do this in order to GET a continent and get all countries and all counties within.

The relationship between them:

  • Continent hasMany Country , and Country owned by Continent
  • Country hasMany County , and County owned by Country

So calling the REST api for /api/Continent/1 returns

 { "id": 1 "name":"Europe" } 

Now I want to get all countries and districts using Continent , so I make a request to /api/Continent/1?filters[include]=country

However, I do not get countys.

What query should I do to get a list that includes both levels of relationships? Like this:

 { "id": 1, "name": "Europe", "country": [ id: 1, name:"United Kingdom", county:[ {id:1,name:"Avon"}, {id:2,name:"Bedfordshire"}, ... ], ... ] } 

Thank you for your help!

+6
source share
2 answers

Syntax:

 /api/Continent/1?filter={"include": {"country": "countys"}} 
+4
source

Hi, hope this is not too late for an answer. After carefully flipping through their documents inside and outside of this problem, I ended up writing a remote method to achieve this deep multiple level. It is not so clear how to do this at the REST api level.

 Continent.listContinents = function(limit,skip,order,cb) { Continent.find({ limit:limit, skip:skip, order:order, include:[{country:'county'}], }, cb); }; Continent.remoteMethod('listContinents', { description:"List continents. Include the related country and county information", returns: {arg: 'continents', type: 'array'}, accepts: [{arg: 'limit', type: 'number', http: { source: 'query' }}, {arg: 'skip', type: 'number', http: { source: 'query' }}, {arg: 'order', type: 'string', http: { source: 'query' }}], http: {path:'/list', verb: 'get'} }); 

I added some additional query string parameters limit, order and skip to enable pagnination and ordering..but not must :)

It is also assumed that you already have relationship types defined between the continent and the country, and then the country and the county.

+2
source

Source: https://habr.com/ru/post/983922/


All Articles