gpt4 book ai didi

node.js - 将嵌套循环查询组合到父数组结果 - pg-promise

转载 作者:搜寻专家 更新时间:2023-10-31 23:07:32 25 4
gpt4 key购买 nike

我是 node(express) 和 pg-promise 的新手,一直无法弄清楚如何将每个嵌套查询(循环)的结果添加到主 json 数组结果查询中。

我有两个表:帖子和评论。

CREATE TABLE post(
id serial,
content text not null,
linkExterno text,
usuario VARCHAR(50) NOT NULL REFERENCES usuarios(alias) ON UPDATE cascade ON DELETE cascade,
multimedia text,
ubicacation VARCHAR(100),
likes integer default 0,
time VARCHAR default now(),
reported boolean default false,
PRIMARY KEY (id) );

CREATE TABLE comment(
id serial,
idPost integer NOT NULL REFERENCES post(id) ON UPDATE cascade ON DELETE cascade,
acount VARCHAR(50) NOT NULL REFERENCES users(alias) ON UPDATE cascade ON DELETE cascade,
content text NOT NULL,
date date default now(),
PRIMARY KEY (id));

所以我想将每个评论的结果添加到每个帖子并返回帖子。我有这个,但不起作用:

con.task(t => {
return t.any('select *, avatar from post, users where user= $1 and user = alias ORDER BY time DESC LIMIT 10 OFFSET $2', [username, pos])
.then(posts => {
if(posts.length > 0){
for (var post of posts){
post.coments = t.any('select * from comment where idPost = $1 ', post.id);
}
}
});
}).then(posts => {
res.send(posts);
}).catch(error => {
console.log(error);
});

有什么建议吗?PD:我想我的问题有点类似于这个: get JOIN table as array of results with PostgreSQL/NodeJS

答案:

选项 1(最佳选择):

通过 JSON 到 psql 进行单个查询(JSON 查询)

See answer by @vitaly-t

Getting the nested data asynchronously using ajax.

选项 2:

function buildTree(t) {
return t.map("select *, avatar from publicacion, usuarios where usuario = $1 and usuario = alias ORDER BY hora DESC LIMIT 10 OFFSET $2", [username, cantidad], posts => {
return t.any('select * from comentario where idPublicacion = $1', posts.id)
.then(coments => {
posts.coments = coments;
console.log(posts.coments);
return posts;
});
}).then(t.batch); // settles the array of generated promises
}

router.get('/publicaciones', function (req, res) {
cantidad = req.query.cantidad || 0; //num de publicaciones que hay
username = req.session.user.alias;

con.task(buildTree)
.then(data => {
res.send(data);
})
.catch(error => {
console.log(error);
});
});

选项 3(异步):

try{
var posts = await con.any('select *, avatar from post, users where user = $1 and user = alias ORDER BY time DESC LIMIT 10 OFFSET $2', [username, q])
for (var post of posts){
post.coments = await con.any('select * from comment where idPublictcion = $1', post.id);
}
}catch(e){
console.log(e);
}

最佳答案

我是 pg-promise 的作者;)


con.task(t => {
const a = post => t.any('SELECT * FROM comment WHERE idPost = $1', post.id)
.then(comments => {
post.comments = comments;
return post;
});
return t.map('SELECT *, avatar FROM post, users WHERE user = $1 AND user = alias ORDER BY time DESC LIMIT 10 OFFSET $2', [username, pos], a)
.then(t.batch);
})
.then(posts => {
res.send(posts);
})
.catch(error => {
console.log(error);
});

另请参阅此问题:get JOIN table as array of results with PostgreSQL/NodeJS .

更新

如果您不想一直使用 JSON 查询方法,那么以下方法将比原始解决方案更好地扩展,因为我们连接所有子查询,然后将它们作为一个查询执行:

con.task(async t => {
const posts = await t.any('SELECT *, avatar FROM post, users WHERE user = $1 AND user = alias ORDER BY time DESC LIMIT 10 OFFSET $2', [username, pos]);
const a = post => ({query: 'SELECT * FROM comment WHERE idPost = ${id}', values: post});
const queries = pgp.helpers.concat(posts.map(a));
await t.multi(queries)
.then(comments => {
posts.forEach((p, index) => {
p.comments = comments[index];
});
});
return posts;
})
.then(posts => {
res.send(posts);
})
.catch(error => {
console.log(error);
});

查看 API:

关于node.js - 将嵌套循环查询组合到父数组结果 - pg-promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50391680/

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