【问题标题】:Can Sails query two tables at the same time?Sails 可以同时查询两个表吗?
【发布时间】:2015-09-25 17:15:07
【问题描述】:

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

我有两个表“Person”和“Pet”。

对于'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( ... )

【问题讨论】:

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


    【解决方案1】:

    这里需要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')
        // ...
    

    但是不存在嵌套种群,issue discussion here

    【讨论】:

    • 感谢您的回答。它解释得很好。还有一个问题。我发现查询:Person.find({age: {'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多