2015-09-25 29 views
1

我想用Sails查詢語言來查詢兩個表,Postgresql作爲數據庫。Can Sails可以同時查詢兩張表嗎?

我有兩張桌子'人'和'寵物'。

對於「人」,它的型號是:

id: { type: 'integer', primaryKey } 
namePerson: { type: 'string' } 
age: { type: 'integer' } 

爲「寵物」,它的型號是:

id: { type: 'integer', primaryKey } 
owner: { model: 'Person' } 
namePet: { type: 'string' } 

我想找到誰是人比年輕人擁有的所有寵物12,我想在一個查詢中完成。那可能嗎?

我只知道如何做兩個查詢。首先,找到所有誰是12歲以下的人:

Person.find({age: {'<', 12}}).exec(function (err, persons) {..}; 

然後,找到他們所擁有的所有寵物:

Pet.find({owner: persons}).exec(...) 

回答

2

您在這裏one-to-many association(一個人可以有多個寵物)需要。

你的人應該與寵物相關:

module.exports = { 

    attributes: { 
     // ... 
     owner:{ 
      model:'person' 
     } 
    } 
} 

,您仍然可以按年齡標準查找用戶:

Person 
    .find({age: {'<', 12}}) 
    .exec(function (err, persons) { /* ... */ }); 

module.exports = { 

    attributes: { 
     // ... 
     pets:{ 
      collection: 'pet', 
      via: 'owner' 
     } 
    } 
} 

你的寵物應該與人的關聯用他的寵物取用戶應該填充關聯:

Person 
    .find({age: {'<', 12}}) 
    .populate('pets') 
    .exec(function(err, persons) { 
     /* 
     persons is array of users with given age. 
     Each of them contains array of his pets 
     */ 
    }); 

帆允許您在一個查詢一樣執行多個人口:

Person 
    .find({age: {'<', 12}}) 
    .populate('pets') 
    .populate('children') 
    // ... 

但嵌套的人羣是不存在的,問題discussion here

+0

謝謝你的回答。這很好解釋。還有一個問題。我發現查詢:Person.find({age:{'<',12}})。populate('pets')也返回沒有寵物的人,即{... pets:[] ...}。只有至少有一個寵物的人可以返回嗎?謝謝。 – JustWonder