Can Sails可以同时查询两个表吗?
我正在尝试使用Sails查询语言来查询两个表,Postgresql作为数据库。
我有两张桌子“人”和“宠物”。
对于“人”,其模型是:
id: { type: 'integer', primaryKey } namePerson: { type: 'string' } age: { type: 'integer' }
对于“宠物”,其模型是:
id: { type: 'integer', primaryKey } owner: { model: 'Person' } namePet: { type: 'string' }
我想find所有由12岁以下的人所有的宠物,我想在一个查询中做到这一点。 那可能吗?
我只知道如何做两个查询。 首先find所有年龄小于12岁的人:
Person.find({age: {'<', 12}}).exec(function (err, persons) {..};
然后,find他们拥有的所有宠物:
Pet.find({owner: persons}).exec( ... )
这里需要一对多的关联 (一个人可以有几个宠物)。
你的人应该与宠物有关联:
module.exports = { attributes: { // ... pets:{ collection: 'pet', via: 'owner' } } }
你的宠物应该与人联系在一起:
module.exports = { attributes: { // ... owner:{ model:'person' } } }
您仍然可以按年龄标准find用户:
Person .find({age: {'<', 12}}) .exec(function (err, persons) { /* ... */ });
用他的宠物提取用户,你应该填充关联:
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') // ...
但是嵌套的人口是不存在的, 在这里讨论 。