node.js - Sails可以同时查询两个表吗?

标签 node.js sails.js sails-postgresql

我正在尝试使用 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/

相关文章:

node.js - 在 SailsJS 中维护模型更新历史

postgresql - sailspostgresql 使用 sails lift 命令时出错?

node.js - 如何使用 RequireJS 运行 jasmine-node 测试

javascript - socket.io 不记录控制台消息

javascript - Node.js 变量声明和范围

node.js - 压入数组返回 Object 对象

node.js - 我可以从命令行运行 sailsjs Controller 方法吗?

javascript - Sailsjs从两个不同的mysql数据库获取数据

sails.js - 如何在 Sails js 中使用 bigserial 作为主键 id

javascript - 使用请求库将网站的 HTML 获取到变量中