【问题标题】:Multi-level include filter with LoopBack JS使用 LoopBack JS 的多级包含过滤器
【发布时间】:2015-03-17 16:10:00
【问题描述】:

我的问题是我无法弄清楚如何在一个请求中使用 LoopBack 后端获取多级关系结构。我有 3 个模型:ContinentCountryCounty。我想做的是获得一个大陆,并接收所有国家和其中的所有县。

它们之间的关系:

  • Continent hasMany Country, Country 属于Continent
  • Country hasMany County, County 属于Country

所以对/api/Continent/1的REST api调用返回

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

现在,我想得到Continent的所有国家和县,所以我向/api/Continent/1?filters[include]=country查询

不过,我不知道县。

我应该进行什么样的查询才能获得包含两个关系级别的列表?像这样:

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

感谢您的帮助!

【问题讨论】:

  • 为什么这被否决了?我试图让它尽可能清晰,我很乐意做进一步的改进。
  • 这不是重复的。这也是一个非常有效的问题。希望有人能给出答案。面临同样的问题!

标签: loopbackjs strongloop


【解决方案1】:

语法是:

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

【讨论】:

    【解决方案2】:

    您好,希望现在回答还为时不晚。在彻底翻阅了他们关于这个问题的文档后,我最终编写了一个远程方法来实现深层多重包含。目前还不清楚如何在 REST api 级别进行。

    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'}
    });
    

    我添加了一些额外的查询字符串参数limit、order和skip来启用分页和排序..但不是必须的:)

    这也是假设您已经定义了 Continent 和 Country 以及 Country 和 County 之间的关系类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-29
      • 2017-04-09
      • 1970-01-01
      • 2019-06-24
      • 2020-09-22
      • 1970-01-01
      相关资源
      最近更新 更多