REST级别2(相关模型)范围 – strongloop api

我在文档中发现, 范围使您能够指定可以在模型上作为方法调用引用的常用查询。 下面我有一个categories模型。 我正在尝试创build适用于与模型games关系的范围。 不幸的是,下面什么也没做 如何获得范围适用于关系如下所示?

GET /Categories/{id}/games – 这会得到所有的游戏

通用/模型/ category.json

 "relations": { "categories": { "type": "hasMany", "model": "game", "foreignKey": "" } }, 

/common/models/game.json

  "scopes": { "mature": {"where": {"mature": true}} }, "validations": [], "relations": { "category": { "type": "belongsTo", "model": "category", "foreignKey": "" } } 

我希望能够通过endpoing获得数据: /Categories/{id}/games/mature

表格模式:

 catgories category_name category_id ------------- ----------- fighting 1001 racing 1002 sports 1003 games game_id game_name category_id mature ----------- ------------ ----------- -------------- 13KXZ74XL8M Tekken 10001 true 138XZ5LPJgM Forza 10002 false 

Loopback API是基于swaggerscopes是loopback中的一个新概念。

目前它不支持相关的方法,即你不能从相关的模型(即你的情况)访问它,而只能从scope被定义的模型,即game

因此,你可以使用远程方法来实现你想要的东西。

通过使用Remote Methods 。 环回远程方法

common / models / category.js添加以下行。

 module.exports = function(Category) { Category.mature = function(id, filter, callback) { var app = this.app; var Game = app.models.Game; if(filter === undefined){ filter = {}; } filter.where = filter.where || {}; filter.where.categoryId = id; filter.where.mature = true; Game.find(filter, function(err, gameArr) { if (err) return callback(err); console.log(gameArr); callback(null, gameArr); }); } Category.remoteMethod( 'mature', { accepts: [{ arg: 'id', type: 'number', required: true }, { arg: 'filter', type: 'object', required: false } ], // mixing ':id' into the rest url allows $owner to be determined and used for access control http: { path: '/:id/games/mature', verb: 'get' }, returns: { arg: 'games', type: 'array' } } ); }; 

现在在你的common / models / category.json中添加这个到你的ACL属性。

 ..... ..... "acls": [ { "principalType": "ROLE", "principalId": "$everyone", "permission": "ALLOW", "property": "mature" } ] 

现在你可以通过get method http://0.0.0.0:3000/api/categories/:id/games/mature

或者,您现在也可以从loopback-explorer尝试API。