LoopBack访问另一个模型
这是情况:
我有三个模型我的数据库:
口袋妖怪/口袋妖怪types/types
口袋妖怪通过口袋妖怪types链接到一个或多个types。
所以现在我想要一个函数来获得链接到给定口袋妖怪的types:
module.exports = function(Pokemon) { Pokemon.types = function(id, cb){ var PokemonType = Pokemon.app.models.pokemonType.find(); var Type = Pokemon.app.models.type.find(); var arrayTypes = []; // var result = app.models.pokemonType.find({where : {"pokemon_id": id}}); // for(var x in result){ // var typeId = x.pokemonType_id; // var results = Type.find({where: {"id": typeId}}); // arrayTypes.push(results); // } cb(null, PokemonType[0] + " AND " + Type); } Pokemon.remoteMethod( 'types', { accepts: {arg: 'id', type:'number', required:true, http: { source: 'header' }}, returns: {arg: 'types', type:'object' }, http: {path: '/types', verb: 'get', status: 200, errorStatus: 400} } ); };
我试图从PokemonType表的结果中findtypes。 所以如果有一行与当前的PokemonID,我想要属于这个typesPokemonType行的types表。
然而,当试图用模型做到这一点,我不断得到未定义和[对象对象]。
我知道,如果我使用Pokemon.find它使用表来search口袋妖怪,但它有相同的实例,如果我searchPokemonType与给定的PokemonID? 还是我的思维完全错了?
我是什么意思? 我期待这一点:
PokemonType.find({where :{ "pokemon_id": id}});
行为相同:
Pokemon.find({where: { "id": id}});
但是有正确的答案。
如何解决未定义的问题? 那我怎么才能得到正确的types链接到口袋妖怪?
解决scheme发现
Pokemon.types = function(id, cb){ var PokemonType; var curPokemon = {"pokemon":null, "type": null}; var Type; var arrayTypes = new Array(); var count; Pokemon.find({where: {"id": id}}) .then(result => { if(result.length > 0){ curPokemon.pokemon = result[0]; Pokemon.app.models.pokemonType .find({where:{"pokemon_id": id}}) .then(result => { count = result.length result.forEach(function(item, index){ Pokemon.app.models.type .find({where:{"id": item.type_id}}) .then(result => { if(result.length > 0){ arrayTypes.push(result[0]); if(arrayTypes.length == count){ curPokemon.type = arrayTypes; cb(null, curPokemon); } } }); }); }); } }); }
通过使用MainModel.app.models.ModelIWant我可以得到正确的模型实例。 然后使用.find并在promise(.then)中使用我的逻辑。
这使我得到正确的结果,然后使用这些结果来获得正确的数据。 然后通过用curPokemon创build自己的模型(对象),我可以修改结果,以便将所需的数据添加到MainModel。