I use the pg-promise
library with bluebird
for making dependent queries.
I have two tables, a and b, looking like this:
| a | | b |
|-------| |-------|
| a_id | | b_id |
| prop1 | | prop2 |
| b_a |
where b.b_a
is a reference to a.a_id
. I want to select all entries matching a given prop1
and the result should contain all matching a
-rows plus the corresponding b
-rows for each a
. This should be doable with two dependent queries. Both queries may return multiple results.
If table a
only returns one row I can do this:
function getResult(prop1) {
return db.task(function (t) {
return t.one("select * from a where prop1=$1", prop1)
.then(function (a) {
return t.batch([a, t.any("select * from b where b_a=$1", a.a_id)]);
})
.then(function (data) {
var a = data[0];
var bs = data[1];
bs.forEach(function (b) {
b.a = a;
});
return bs;
});
});
}
And I'm also able to get all matching b
-entries for multiple a
-results like this:
function getResult(prop1) {
return db.task(function (t) {
return t.many("select * from a where prop1=$1", prop1)
.then(function (as) {
var queries = [];
as.forEach(function (a) {
queries.push(t.any("select * from b where b_a=$1", a.id));
});
return t.batch(queries); // could concat queries with as here, but there wouldn't be a reference which b row belongs to which a row
})
.then(function (data) {
// data[n] contains all matching b rows
});
});
}
But how to bring those two together?
as[n]
together withdata[n]
. Have a look here on how to accessas
. – Dzerzhinska
andb
, so the indizes are not helpful here.. – Canonicalbatch
? Isn'tdata
a two-dimensional array of some kind? – Dzerzhinskwhere a.a_b is a reference
- there is noa_b
in tablea
. – Timepiecethe result should contain all matching a-rows plus the corresponding b-rows for each a.
do you want a single object with the tree or an array of some sort? Not clear exactly what type of output you want. – Timepiece