2014-09-01 33 views
1

如何根据关联表中的字段对集合进行搜索?如何根据Waterline协会中的字段搜索记录?

如果我们使用Waterline文档(https://github.com/balderdashy/waterline-docs/blob/master/associations.md)中的用户和宠物的标准示例,是否有可能例如搜索拥有特定品种宠物的所有用户(找到我所有的狗主, 例如)?

是它像那样简单:提前

User.find() 
    .populateAll() 
    .where({ 
     type: 'dog', 
     breed: 'scotch collie' 
    }) 
    .then(function (lassies) { 
     // ... 
    }); 

感谢。

回答

2

目前无法通过关联进行搜索(截至Sails v0.10.x)。出于您的目的,最好的解决方案可能是搜索某个品种的所有宠物,填充它们的所有者,并连接列表。就像:

Pet.find({type: 'dog', breed: 'scotch collie'}) 
    .populate('owners') 
    .exec(function(err, dogs) { 

     // Concatenate all the associated owners into one array using reduce, 
     // then remove duplicates using uniq and the "id" attribute   
     var owners = _.uniq(_.reduce(dogs, function(memo, dog) { 

      return memo.concat(dog.owners);    

     }, []), 'id'); 

}); 
+0

谢谢,我不认为这是可能的。我可能会最终创建一个视图来解决它。 – 2014-09-03 23:49:26

+0

这仍然是这种情况?你不能通过关联进行搜索? – iwayneo 2015-03-06 07:16:39

相关问题