node.js - 使用 pg-promise 查询多对多关系的最佳方法

标签 node.js postgresql express pg-promise

例如,我想从数据库中获取用户信息、电子邮件及其角色,并创建一个对象,如:

{
  "id": 1,
  "firstname": "John",
  "lastname": "Johnny",
  "emails": [
    {
      "type": "work",
      "email": "work@work.com"
    },
    {
      "type": "personal",
      "email": "personal@personal.com"
    }
  ],
  "roles": [
    {
      "role": "ADM",
      "title": "Admin"
    },
    {
      "role": "PUB",
      "title": "Publisher"
    }
  ]
}

我需要查询三个表:

  • Users 表有 idfirstnamelastname
  • Emails 表有typeemailuser_id
  • Roles 表有roletitleuser_id

基于pg-promise的 wiki 我几乎可以肯定它必须使用 Tasks 来完成但不确定您将如何链接它们。

更新 在我的实际项目中,我必须插入一个产品并使用生成的 ID 来插入属性。如果您遇到类似情况,请在此处添加我的代码:

//Insert a new product with attribites as key value pairs
post_product_with_attr: function(args) {
    return db.task(function(t) {
        return t.one(sql.post_new_product, args)
            .then(function(dt) {
                var queries = [];
                Object.keys(args).forEach(function(key) {
                    queries.push(t.one(sql.post_attr_one, { Id: dt.id, key: key, value: args[key] }));
                 });
                return queries.length ? t.batch(queries) : [dt];
            });
    });
}

最佳答案

您所描述的不是多对多关系,而是 2 个一对多关系。

Based on the pg-promise's wiki I am almost sure it has to be done using Tasks but not sure how would you chain them.

在您的示例中,无需链接任何内容。当一个结果需要用作下一个的条件时,一个链会 promise promise ,因为这就是 promise 的工作方式,而不仅仅是查询。

因此,您可以并行或独立地执行所有 3 个查询,如下例所示:

function getUserInfo(userId) {
    return db.task(async t => {
        const user = await t.one('SELECT id, firstname, lastname FROM Users WHERE id = $1', userId);
        const emails = await t.any('SELECT type, email FROM emails WHERE user_id = $1', userId),
        const roles = await t.any('SELECT role, title FROM roles WHERE user_id = $1', userId);

        user.emails = emails;
        user.roles = roles;

        return user;
});

使用示例:

const user = await getUserInfo(123); //=> user object with all details

请注意,通过现有的 PostgreSQL JSON 函数执行此操作效率更高,这样您就可以只执行一个查询。

关于node.js - 使用 pg-promise 查询多对多关系的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36586486/

相关文章:

node.js - 运行测试时“描述未定义”

javascript - 检索在 Objection ORM 中的 $afterInsert Hook 中创建的模型的 ID

node.js - 快速 Handlebars : Getting current URL query and passing query to a template?

node.js - Mongoose :.findById 不是函数

javascript - 使用pm2时如何自动重新加载Node.js项目

node.js - 删除帖子及其所有通知和提要

postgresql - postgres中是否有低优先级查询之类的东西?

匹配的正则表达式以

PostgreSQL 9.3 : changing the value of SYSTEM parameters like log_lock_waits

node.js - app.render() 可以渲染 View 数组吗?