gpt4 book ai didi

javascript - 使用 pg-promise 获取父子树

转载 作者:行者123 更新时间:2023-11-29 10:35:17 24 4
gpt4 key购买 nike

我将 pg-promise 库与 bluebird 一起用于进行相关查询。我有两个表,a 和 b,如下所示:

|   a   |     |   b   |  
|-------| |-------|
| a_id | | b_id |
| prop1 | | prop2 |
| b_a |

其中 b.b_a 是对 a.a_id 的引用。我想选择与给定 prop1 匹配的所有条目,结果应包含所有匹配的 a-行加上每个 b 的相应行 一个。这应该可以通过两个相关查询来实现。两个查询都可能返回多个结果。

如果表 a 只返回一行,我可以这样做:

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;
});
});
}

而且我还能够为多个 a - 结果获取所有匹配的 b 条目,如下所示:

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
});
});
}

但是如何将这两者结合起来呢?

最佳答案

我是 pg-promise 的作者.


当您有 2 个表:Parent -> Child 具有一对多关系,并且您希望获得匹配的 Parent 数组code> 行,每行扩展属性 children 设置为表 Child ...

中相应行的数组

有几种方法可以实现这一点,如 pg-promise 的组合并且 promises 通常是非常灵活的。这是最短的版本:

db.task(t => {
return t.map('SELECT * FROM Parent WHERE prop1 = $1', [prop1], parent => {
return t.any('SELECT * FROM Child WHERE parentId = $1', parent.id)
.then(children => {
parent.children = children;
return parent;
});
}).then(a => t.batch(a))
})
.then(data => {
/* data = the complete tree */
});

这就是我们在那里所做的:

首先,我们查询 Parent 项,然后将每一行映射到对相应 Child 项的查询,然后将其行设置到 Parent 并返回它。然后我们使用方法batch解析从方法 map 返回的 Child 查询数组.

ES7 更新

这里和上面一样,但是使用了ES7的async/await语法:

await db.task(async t => {
const parents = await t.any('SELECT * FROM Parent WHERE prop1 = $1', [prop1]);
for(const p of parents) {
p.children = await t.any('SELECT * FROM Child WHERE parentId = $1', [p.id]);
}
return parents;
});
// the task resolves with the correct data tree

任务将使用这样的数组来解决:

[
{
"parent1-prop1", "parent1-prop2",
"children": [
{"child1-prop1", "child1-prop2"},
{"child2-prop1", "child2-prop2"}
]
},
{
"parent2-prop1", "parent2-prop2",
"children": [
{"child3-prop1", "child3-prop2"},
{"child4-prop1", "child4-prop2"}
]
}
]

API 引用:map , batch

更新

查看更好的答案:JOIN table as array of results with PostgreSQL/NodeJS .

关于javascript - 使用 pg-promise 获取父子树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37664258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com