SQL relationships to json with golang

huangapple go评论82阅读模式
英文:

SQL relationships to json with golang

问题

我正在学习Go语言。

如果我在MySQL或PostgreSQL数据库中有一个帖子和评论的表关系,例如:

帖子表:id, title
评论表:id, post_id, comment

我想要得到这样的JSON表示:

{
  id: 1,
  title: "一篇博客文章",
  comments: [
      {id: 1, comment: "这是评论1"},
      {id: 2, comment: "这是评论2"}
  ]
}

我已经能够获取帖子并显示JSON,只是无法获取评论。我认为我需要在帖子结构体中有一个评论结构体的数组。只是不确定如何将它们全部联系在一起,特别是行的扫描部分。

一个展示如何从这样的关系中输出JSON的示例将会很好。

英文:

Still learning Go.

If I have a posts and comments table relationship in a mysqp/pg database eg

Post  id, title
Comments  id, post_id, comment

I'd like to have a json representation of this:

{
  id: 1
  title: "A blog post"
  comments: [
      {id: 1, comment: "This is comment 1"},
      {id: 2, comment: "This is comment 2"}
  ]
}

I am able to grab the posts and show the json, just not the comments. I think I need to have an array of Comment structs in the Post struct. Just not sure how to tie it all together, particularly the scanning of the rows.

An example showing outputting json from a relationship like this would be great.

答案1

得分: 3

这是我最近为某人编写的一个示例。

https://gist.github.com/freeeve/9167240

关键部分在这里,将Post替换为Message,将Comments替换为Friends:

msgs := []Message{}
for rows.Next() {
    msg := Message{}
    friend := Friend{}
    err := rows.Scan(&msg.Id, &msg.Name, &msg.Street, &msg.City, &msg.Zip, &msg.State, &msg.Email, &msg.Phone, &friend.Id, &friend.Name)
    if err != nil {
        log.Fatal(err)
    }
    if len(msgs) == 0 || msgs[len(msgs)-1].Id != msg.Id {
        msg.Friends = append(msg.Friends, friend)
        msgs = append(msgs, msg)
    } else {
        msgs[len(msgs)-1].Friends = append(msgs[len(msgs)-1].Friends, friend)
    }
}
英文:

It just so happens I wrote an example for someone recently.

https://gist.github.com/freeeve/9167240

The meat is in here, replace Post with Message and Comments with Friends:

msgs := []Message{}
for rows.Next() {
	msg := Message{}
	friend := Friend{}
	err := rows.Scan(&msg.Id, &msg.Name, &msg.Street, &msg.City, &msg.Zip, &msg.State, &msg.Email, &msg.Phone, &friend.Id, &friend.Name)
	if err != nil {
		log.Fatal(err)
	}
	if len(msgs) == 0 || msgs[len(msgs)-1].Id != msg.Id {
		msg.Friends = append(msg.Friends, friend)
		msgs = append(msgs, msg)
	} else {
		msgs[len(msgs)-1].Friends = append(msgs[len(msgs)-1].Friends, friend)
	}
}

huangapple
  • 本文由 发表于 2014年4月2日 10:22:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/22800353.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定