Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-level include filter with LoopBack JS

My problem is that I can't figure out how to get multilevel relations structures in one request with LoopBack backend. I have 3 models: Continent, Country, County. What I would like to do is to GET a continent, and recieve all the countries, and all the counties within.

The relationship between them:

  • Continent hasMany Country, and Country belongsTo Continent
  • Country hasMany County, and County belongsTo Country

So the REST api call to /api/Continent/1 returns

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

Now, I want to get all the countries and counties with the Continent, so I do a query to /api/Continent/1?filters[include]=country

Still, I don't get the countys.

What kind of query should I make to get a list which includes both relation levels? Like this:

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

Thanks for your help!

like image 441
Mihaly KR Avatar asked Mar 17 '15 16:03

Mihaly KR


2 Answers

The syntax is:

/api/Continent/1?filter={"include": {"country": "countys"}}
like image 53
conradj Avatar answered Oct 09 '22 23:10

conradj


Hello hoping it's not too late for an answer. After a thorough flipping of their docs inside and out on this issue, I ended up writing a remote method to achieve that deep level multiple includes. It's not so clear how to go about it 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 have added some additional query string parameters limit, order and skip to enable pagnination and ordering..but not a must :)

Also this is assuming you already have relation types defined between Continent and Country then Country and County.

like image 32
Opiyo Adamsy Avatar answered Oct 09 '22 22:10

Opiyo Adamsy