node.js - Can Sails query two tables at the same time? -


i trying use sails query language query 2 tables, postgresql database.

i have 2 tables 'person' , 'pet'.

for 'person', model is:

id: { type: 'integer', primarykey } nameperson: { type: 'string' } age: { type: 'integer' } 

for 'pet', model is:

id: { type: 'integer', primarykey } owner: { model: 'person' } namepet: { type: 'string' } 

i want find pets owned people younger 12, , want in single query. possible?

i know how in 2 queries. first, find people younger 12:

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

then, find pets owned them:

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

you need here one-to-many association (one person can have several pets).

your person should associated pets:

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

your pets should associated person:

module.exports = {      attributes: {         // ...         owner:{             model:'person'         }     } } 

you can still find user age criteria:

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

to fetch user pets should populate association:

person     .find({age: {'<', 12}})     .populate('pets')     .exec(function(err, persons) {          /*          persons array of users given age.          each of them contains array of pets         */      }); 

sails allow perform multiple population in 1 query like:

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

but nested populations not exist, issue discussion here.


Comments