微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

惯用的加载方式-如何使用数据库/ sql和pq填充深层嵌套的关联

如何解决惯用的加载方式-如何使用数据库/ sql和pq填充深层嵌套的关联

我只是想知道如何处理急于加载的查询以检索具有多个关联的数据,让我解释一下我的模型:

type User struct {
  Id uint
  Name string
  Username string
  Image string
}

type Post struct {
  Id unit
  Content string
  Author *User // I use user_id in author column for the posts table
  Comments []Comments
}

type Comments struct {
  Id unit
  PostId uint
  Message string
  CommentBy *User // I use user_id in comment_by column for the comments table
}

这是检索到的数据的示例:

{
    "Posts": [
        {
            "Id": 1,"Content": "test post","Author": {
                  "Id": 1,"Name": "author","Username": "h3ll0","Image": "author.png"
            },"Comments": [
                {
                    "Id": 1,"PostId": 1,"Message": "good article","CommentBy": {
                        "Id": 2,"Name": "second user","Username": "r3ader","Image": "reader.png"
                    }
                },{
                    "Id": 2,"Message": "bad article","CommentBy": {
                        "Id": 3,"Name": "third user","Username": "thirD","Image": "third.png"
                    }
                }
            ]
        }
    ]
}

我想检索具有所有嵌套关联的发布数据,并将它们映射到Post结构。您将如何使用database / sql和pq(Postgres驱动程序)来完成此任务?

我根本不想使用任何ORM,我只使用数据库/ sqlsqlx。

请记住,性能非常重要,因为帖子和评论表足够大。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。