7

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!

Mihaly KR
  • 2,363
  • 2
  • 19
  • 20
  • Why was this downvoted? I tried to make it as clear as possible and I'd be happy to do further improvements. – Mihaly KR Mar 17 '15 at 17:36
  • Seems the duplicate of http://stackoverflow.com/questions/26997368/loopback-2-4-how-to-query-certain-fields-of-related-model-via-rest-api – IvanZh Mar 19 '15 at 09:11
  • This is not a duplicate. It's also very valid question. Wish somebody has the answer to it. Facing the same problem! – Anoop Thiruonam Sep 12 '15 at 16:49

2 Answers2

5

The syntax is:

/api/Continent/1?filter={"include": {"country": "countys"}}
conradj
  • 2,481
  • 2
  • 24
  • 30
2

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.