I am trying to use Sails query language to query two tables, with Postgresql as the database.
我试图使用Sails查询语言来查询两个表,使用Postgresql作为数据库。
I have two tables 'Person' and 'Pet'.
我有两个表'人'和'宠物'。
For 'Person', its model is:
对于'人',其模型是:
id: { type: 'integer', primaryKey }
namePerson: { type: 'string' }
age: { type: 'integer' }
For 'Pet', its model is:
对于'Pet',它的模型是:
id: { type: 'integer', primaryKey }
owner: { model: 'Person' }
namePet: { type: 'string' }
I want to find all the pets who are owned by people younger than 12, and I want to do it in a single query. Is that possible?
我想找到12岁以下的人拥有的所有宠物,我想在一个查询中完成。那可能吗?
I only know how to do it in two queries. First, find all the people who are younger than 12:
我只知道如何在两个查询中执行此操作。首先,找到所有12岁以下的人:
Person.find({age: {'<', 12}}).exec(function (err, persons) {..};
Then, find all the pets owned by them:
然后,找到他们拥有的所有宠物:
Pet.find({owner: persons}).exec( ... )
1 个解决方案
#1
2
You need here one-to-many association (one person can have several pets).
你需要这里一对多的关联(一个人可以有几只宠物)。
Your person should be associated with pets:
您的人应该与宠物有关:
module.exports = {
attributes: {
// ...
pets:{
collection: 'pet',
via: 'owner'
}
}
}
Your pets should be associated with person:
您的宠物应该与人联系:
module.exports = {
attributes: {
// ...
owner:{
model:'person'
}
}
}
You can still find user by age criteria:
您仍然可以按年龄标准找到用户:
Person
.find({age: {'<', 12}})
.exec(function (err, persons) { /* ... */ });
To fetch user with his pets you should populate association:
要使用他的宠物获取用户,您应该填充关联:
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 allow you to perform multiple population in one query like:
Sails允许您在一个查询中执行多个填充,如:
Person
.find({age: {'<', 12}})
.populate('pets')
.populate('children')
// ...
But nested populations is not exist, issue discussion here.
但是嵌套的人口不存在,在这里讨论问题。
#1
2
You need here one-to-many association (one person can have several pets).
你需要这里一对多的关联(一个人可以有几只宠物)。
Your person should be associated with pets:
您的人应该与宠物有关:
module.exports = {
attributes: {
// ...
pets:{
collection: 'pet',
via: 'owner'
}
}
}
Your pets should be associated with person:
您的宠物应该与人联系:
module.exports = {
attributes: {
// ...
owner:{
model:'person'
}
}
}
You can still find user by age criteria:
您仍然可以按年龄标准找到用户:
Person
.find({age: {'<', 12}})
.exec(function (err, persons) { /* ... */ });
To fetch user with his pets you should populate association:
要使用他的宠物获取用户,您应该填充关联:
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 allow you to perform multiple population in one query like:
Sails允许您在一个查询中执行多个填充,如:
Person
.find({age: {'<', 12}})
.populate('pets')
.populate('children')
// ...
But nested populations is not exist, issue discussion here.
但是嵌套的人口不存在,在这里讨论问题。