如何使用loopback.io将相关实体包含在REST中

我正在使用Strongloop的环回工具来创build一个REST服务。 我想知道如何定义什么相关的实体,当请求一个模型返回。

我在文档中看到,你可以发送一个像GET /api/members?filter[include]=posts这样的请求GET /api/members?filter[include]=posts并且会返回相关的post模型,并且我发现你可以做一个像GET /api/members?filter[include]=posts&filter[include]=comments这样的请求GET /api/members?filter[include]=posts&filter[include]=comments来获取post和评论,但有没有一种方法可以在代码或生成的json文件中定义,您希望某个关系在请求模型时总是被返回?

预设的filter属性被称为默认范围。 我们有一个挂起的请求来支持。 请参阅https://github.com/strongloop/loopback-datasource-juggler/pull/296

作为特性发布之前的解决方法,您可以使用beforeRemote钩子来使用默认范围更新filter对象。 请参阅http://docs.strongloop.com/display/LB/Defining+remote+hooks

您可以使用两种不同的简单方法与帐户build立关系。

  1. 在Model.json文件中使用模型定义。

     "validations": [], "relations": { "team": { "type": "belongsTo", "model": "Team", "foreignKey": "" }, "user": { "type": "belongsTo", "model": "User", "foreignKey": "" } } 

这将始终使用直接关系将一个模型与另一个模型绑定,并且可以使用以下代码行来检索它们。

 app.models.TeamRole.findOne({ where: { userId: user.id }, include:[ { relation: 'team' }, { relation: 'user' } ] },function(err,team,user){ //retrieve relational data here }); 
  1. 你可以使用可操作的钩子概念来轻松获得这种关系。

干杯。