我正在尝试使用 Sails 查询语言来查询两个表,以 Postgresql 作为数据库。
我有两个表“人”和“宠物”。
对于“Person”,其模型是:
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( ... )
最佳答案
您需要这里one-to-many association (一个人可以养几只宠物)。
您的人应该与宠物有关:
module.exports = {
attributes: {
// ...
pets:{
collection: 'pet',
via: 'owner'
}
}
}
你的宠物应该与人相关:
module.exports = {
attributes: {
// ...
owner:{
model:'person'
}
}
}
您仍然可以按年龄条件查找用户:
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
*/
});
Sails 允许您在一个查询中执行多次填充,例如:
Person
.find({age: {'<', 12}})
.populate('pets')
.populate('children')
// ...
但是嵌套群体不存在,问题 discussion here .
关于node.js - Sails可以同时查询两个表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32787426/