带有 pg-promise 的条件任务 [英] Conditional task with pg-promise
本文介绍了带有 pg-promise 的条件任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图简单地从表中读取一个值,并基于对其他查询的返回值调用并返回组合结果.
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.
举个简单的例子:表 Users
有 id
、name
和 emailid
假设 emailid
不为空,我们想调用 email 表并返回一个结果,如 { id:[id], name:[name], email:[email]}代码>.
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]}
.
推荐答案
使用 pg 承诺:
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
});
查看 API:Database.map, Database.one.
另见一个相关问题:获取父子树pg-承诺.
注意:更好的方法是使用带有 INNER JOIN
的单个查询.
NOTE: A better approach would use a single query with INNER JOIN
.
这篇关于带有 pg-promise 的条件任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文