这是对之前question的跟进。目前,api可以从共享关系的category
和game
模型进行查询。例如,通过此端点/Categories/1001/games/mature
,我可以列出fighting
类别中mature
设置为true
的所有游戏。但是,我在db table gameInfo
中包含了第三个模型game_info
。因为,我想从这三个表中获取信息,我在db表gamesCategoriesBridge
中包含了一个名为games_categories_bridge
的直通模型。我按照指南设置了HasManyThrough relations。问题是description
和publishedDate
等附加信息未显示在最终结果中。如何正确设置remoteMethod
以完成以下操作?
公共/模型/ category.js
module.exports = function(Category) {
Category.mature = function(id, callback) {
var app = this.app;
var Game = app.models.Game;
Game.find({
"where": {
categoryId: id,
mature: true
}
}, function(err, gameArr) {
if (err) return callback(err);
console.log(gameArr);
callback(null, gameArr);
});
}
Category.remoteMethod(
'mature', {
accepts: [{
arg: 'id',
type: 'number',
required: true
}],
// 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'
}
}
);
};
表架构:
catgories
category_name category_id
------------- -----------
fighting 1001
racing 1002
sports 1003
游戏
game_id game_name category_id mature
----------- ------------ ----------- --------------
13KXZ74XL8M Tekken 10001 true
138XZ5LPJgM Forza 10002 false
game_info
game_id description published_date
----------- ----------- --------------
13KXZ74XL8M Published by Namco. 1994
138XZ5LPJgM Published by Microsoft Studios. 2005
games_categories_bridge
game_id category_id
----------- -----------
13KXZ74XL8M 10001
138XZ5LPJgM 10002
端点:/categories/{id}/games/mature
API响应的期望格式:
games [
{
gameName: 'Tekken',
gameInfo :
[
{
description : 'Published by Namco.',
published_date : '1994'
}
],
categorName: 'fighting',
categoryId: 1001,
mature: true
}
.....
]
答案 0 :(得分:1)
首先在hasMany
和game
模型
game_info
关系
//Now inside remote_method.
Category.mature = function(id, callback) {
var app = this.app;
var Game = app.models.game;
Category.findById(id, {}, function(err, category) {
if (err) return callback(err);
//Now call the Game find method
Game.find({
"where": {
categoryId: id,
mature: true
},
include:'game_info'
}, function(err, gameArr) {
if (err) return callback(err);
gameArr.forEach(function(gameObj, index){
gameObj.categoryName = category.category_name;
});
callback(null, gameArr);
});
});
}