如何在一个模型中使用远程方法从另一个模型返回信息?

所以我设置了一些非常简单的方法来学习如何使用Loopback。

模型如下:

Person - based on built in User model food_pref typeId (number) personId (number) food_type type (string) 

关系:

 Person has many food_prefs (foreign key: personId) food_pref belongs to Person (foreign key: personId) food_pref belongs to food_type (foreign key: typeId) 

一个自动生成的方法被创build,返回基于Person的id的food_prefs。

 People/{id}/foodPrefs 

这返回:

 [ { "typeId": 0, "personId": 0, "id": 0 } ] 

我想要做的是添加一个名为“getPrefs”的单独的远程方法,该方法根据food_pref中的typeId返回food_type下的types名称。

所以我们假设typeId是1,而food_types中的id是Italian Food,那么远程方法会返回:

 { "type": "Italian Food" } 

我被告知使用Person.js,并添加了一些东西,但是我对include语句以及括号内的操作感到困惑。 通常它崩溃与错误说:错误:关系“food_pref”未定义为人模型,请参阅他们在下面推荐:

 module.exports = function(Person) { Person.getPrefs = function(personId, cb) { Person.findById(personId, { include: { food_pref: "food_type" } }, function(err, user) { if (err) throw err; }); } Person.remoteMethod ( 'getPrefs', { http: {path: '/getPrefs', verb: 'get'}, accepts: {arg: 'personId', type: 'number', http: { source: 'query' } }, returns: {arg: 'type', type: 'string'} } ); }; 

我在这里做错了什么?

编辑:

根据strongloop文档,当你定义一个个人的远程方法时,strongloop会自动提供一个callback,如果需要的话会返回数据。 看下面更新的代码

你想要在food_pref中包含food_pref关系以及food_type realation。 把它放到你的getPrefs自定义方法中:

 Person.getPrefs = function(personId, cb) { Person.findById(personId, { include: [{ relation: 'food_pref', scope: { include: { relation: 'food_type' }}} ]}, function(err, personFound) { if (err) console.log(err); else { cb(null, personFound) } }); }; 

它的作用是:用personId参数和一个cb参数(通过strongloop自动传递)调用你的个人方法。 你的方法通过idfind合适的人,包括关系(食物types的名字),当结果被提取时,“Person.findById”中的callback调用callback“cb” personFound)

 Person.remoteMethod( 'getPrefs', { http: {path: '/:personId/getPrefs', verb: 'get'}, accepts: [{arg: 'personId', type: 'number'}], returns: {arg: 'person', type: 'object'}, description: ['a person object'] } ); 

那么返回的对象应该包含食物types的名称。 确保在Person.json中包含正确的关系名称等等。

如果你只是想要食物的名字,用不同的方法遵循相同的想法:

  • 只需将对象内的string发送到自动callback参数“cb”(并修改注册以宣布您的方法发送的返回types)

  • 在“where”条件下直接在food_type表中search(其中personId =您正在查找的人员的ID)

看看链接到strongloop文档的链接,因为它是关于远程方法的漂亮而详细的。

希望它有帮助。