Multi-level include filter with LoopBack JS
Asked Answered
O

2

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!

Oxblood answered 17/3, 2015 at 16:10 Comment(3)
Why was this downvoted? I tried to make it as clear as possible and I'd be happy to do further improvements.Oxblood
Seems the duplicate of #26997868Runofthemill
This is not a duplicate. It's also very valid question. Wish somebody has the answer to it. Facing the same problem!Zsolway
S
5

The syntax is:

/api/Continent/1?filter={"include": {"country": "countys"}}
Swarm answered 24/9, 2015 at 9:59 Comment(0)
B
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.

Benefactress answered 24/9, 2015 at 7:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.