Can Sails可以同时查询两个表吗?

时间:2015-09-25 17:15:08

标签: node.js sails.js sails-postgresql

我正在尝试使用Sails查询语言来查询两个表,使用Postgresql作为数据库。

我有两个表'Person'和'Pet'。

对于'人',其模型是:

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

对于'Pet',其模型是:

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( ... )

1 个答案:

答案 0 :(得分:2)

你需要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

相关问题