2014-09-01 57 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