我只是想知道如何处理急切加载查询以检索具有多个关联的数据,让我解释一下我的模型:
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,
"PostId": 1,
"Message": "bad article",
"CommentBy": {
"Id": 3,
"Name": "third user",
"Username": "thirD",
"Image": "third.png"
}
}
]
}
]
}
我想检索具有所有嵌套关联的帖子数据并将它们映射到 Post 结构。您将如何使用 database/sql 和 pq(Postgres 驱动程序)?
我根本不想使用任何 ORM,我只使用数据库/SQL 和 SQLx。
请记住,性能很重要,因为帖子和评论表足够大。