Conditional task with pg-promise

本秂侑毒 提交于 2019-12-22 00:52:37

问题


I am trying to simply read a value from a table and based on the return value call for additional queries and return the combined results.

let's take a simple example: table Users has id, name and emailid and let's say if emailid is not null we want to call the email table and return a results like { id:[id], name:[name], email:[email]}.


回答1:


Using the latest syntax supported by pg-promise:

db.task(t => {
    return t.map('SELECT * FROM Users', [], user => {
        return user.emailid ?
            t.one('SELECT * FROM Emails WHERE id = $1', user.emailid, e=> {
                user.email = e.email;
                return user;
            }) : user;
    }).then(t.batch);
})
    .then(data => {
        // success
    })
    .catch(error => {
        // error
    });

See the API: Database.map, Database.one.

See also a related question: Get a parents + children tree with pg-promise.


NOTE: A better approach would use a single query with INNER JOIN.



来源:https://stackoverflow.com/questions/38089864/conditional-task-with-pg-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!