【问题标题】:Nested query from postgresql and pg-promise来自 postgresql 和 pg-promise 的嵌套查询
【发布时间】:2018-10-04 19:28:01
【问题描述】:

我正在尝试使用 pg-promise 从节点中的 postgres 检索嵌套查询。

我只能从表中检索包含混合数据的简单非嵌套结果。

我想从三个表(用户、帖子、cmets)中为每个帖子获取一个数据集 - users.username、posts.text、post.timestamp、cmets.author、cmets.text、cmets.timestamp。用户和帖子与用户名关联,帖子和cmets与posts.id和cmets.parrent关联。

这是我要获取的数据:

[
 {"username": "jane", 
 "postText": "Hello", 
  "postId": 4,
  "postTimestamp: "1651156414", 
  allComments: [
       {"commentsId": 2,
        "commentsAuthor": "john", 
        "commentsText": "nice", 
        "commentsTimestamp": "156454565456"
        }, 
       {"commentsId": 3,
        "commentsAuthor": "ghost",
       "commentsText": "hiii", 
       "commentsTimestamp": "165165848"}]
   }]

我正在使用 pg-promise:

function getUsers(t) {
    return t.map('SELECT * FROM posts', post=> {
        return t.map('SELECT * FROM users WHERE users.username = post.username', post.id, user => {
        return t.any('SELECT * FROM comments, posts WHERE comments.parrent = post.id', user.id)
        .then(comment => {
              user.comment = comment;
                return user;
                });
        })
            .then(t.batch) 
            .then(user=> {
              post.user = user;
                return post;
            });
    }).then(t.batch); 
}

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

});

它给了我错误:

  TypeError: undefined is not a function at Array.map (<anonymous>) at obj.any.call.then.data

您有什么想法吗,我做错了什么?谢谢

【问题讨论】:

标签: javascript sql node.js postgresql pg-promise


【解决方案1】:

问题出在这一行:

return t.map('SELECT * FROM posts', post => {

应该是:

return t.map('SELECT * FROM posts', [], post => {

您将函数作为格式化参数传递,因此出现了问题。

但一般而言,this post 通过 JSON 函数 json_build_object 提供了一个更出色的解​​决方案,因为您将只执行一个查询,而不是您尝试的多个查询。

【讨论】:

  • 非常感谢。我也会尝试您提到的第二种解决方案。
猜你喜欢
  • 1970-01-01
  • 2017-03-09
  • 2017-10-02
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-30
  • 2017-08-29
相关资源
最近更新 更多