帆/水线:如何在关系中检索关系



我需要检索一个对象,还需要获取关系和嵌套关系。

所以,我有下面三个模型:

用户模式:

module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    pets: {
      collection: 'pet',
      via: 'owner',
    }
}
宠物模型:

module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    owner: {
      model: 'user'
    },
    vaccines: {
      collection: 'vaccine',
      via: 'pet',
    }
}
疫苗模型:

module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    pet: {
      model: 'pet'
    }
}

呼叫User.findOne(name: 'everton').populate('pets').exec(....),我得到用户和关联的宠物。我怎样才能获得每只宠物的相关疫苗?我没有在官方文档中找到这方面的参考

我也遇到过这个问题,据我所知,嵌套关联查询还没有内置到帆中(截至本文)。

你可以使用promise来为你处理嵌套的填充,但是如果你要填充许多关卡,这可能会变得相当棘手。

类似:

User.findOne(name: 'everton')
  .populate('pets')
  .then(function(user) {
    user.pets.forEach(function (pet) {
      //load pet's vaccines
    });
  });

这在sails.js上是一个被广泛讨论的话题,实际上有一个开放的pull请求添加了这个功能的大部分。查看https://github.com/balderdashy/waterline/pull/1052

虽然Kevin Le的答案是正确的,但它可能会变得有点混乱,因为您在循环中执行异步函数。当然它是有效的,但是假设你想在游戏完成后返回给用户所有的宠物和疫苗——你该怎么做呢?

有几种方法可以解决这个问题。一种是使用async库,它提供了一堆util函数来处理异步代码。该库已经包含在sails中,默认情况下您可以全局使用它。

 User.findOneByName('TestUser')
   .populate('pets')
   .then(function (user) {
     var pets = user.pets;
     // async.each() will perform a for each loop and execute
     // a fallback after the last iteration is finished
     async.each(pets, function (pet, cb) {
       Vaccine.find({pet: pet.id})
         .then(function(vaccines){
           // I didn't find a way to reuse the attribute name
           pet.connectedVaccines = vaccines;
           cb();
         })
     }, function(){
       // this callback will be executed once all vaccines are received 
       return res.json(user);
     });
   });

还有另一种方法可以解决这个问题,即使用蓝鸟承诺,这也是风帆的一部分。它可能比前一个更高效,因为它只需要一个数据库请求就可以获取所有疫苗。另一方面,它更难读…

User.findOneByName('TestUser')
  .populate('pets')
  .then(function (user) {
    var pets = user.pets,
        petsIds = [];
    // to avoid looping over the async function 
    // all pet ids get collected...
    pets.forEach(function(pet){
      petsIds.push(pet.id);
    });
    // ... to get all vaccines with one db call 
    var vaccines = Vaccine.find({pet: petsIds})
      .then(function(vaccines){
        return vaccines;
      });
    // with bluebird this array...
    return [user, vaccines];
  })
  //... will be passed here as soon as the vaccines are finished loading
  .spread(function(user, vaccines){
    // for the same output as before the vaccines get attached to 
    // the according pet object
    user.pets.forEach(function(pet){
      // as seen above the attribute name can't get used 
      // to store the data
      pet.connectedVaccines = vaccines.filter(function(vaccine){
        return vaccine.pet == pet.id;
      });
    });
    // then the user with all nested data can get returned
    return res.json(user);
  });

最新更新