Conditional task with pg-promise

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

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

+1
source share
1 answer

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 API: Database.map , Database.one .

See also the corresponding question: Get parent tree + tree with pg promises .


NOTE. . A more convenient approach would be to use a single query with an INNER JOIN .

+1
source

Source: https://habr.com/ru/post/1257581/


All Articles