2014-04-02 22 views
0

繼續學習Go。與golang的json的SQL關係

如果我有一個mysqp/PG數據庫如文章和評論表關係

Post id, title 
Comments id, post_id, comment 

我想有這樣的JSON表示:

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

我能抓住帖子並顯示json,而不是評論。我想我需要在Post結構中有一個Comment結構數組。只是不知道如何將它們結合在一起,尤其是掃描行。

一個顯示從這樣的關係中輸出json的例子會很棒。

回答

2

恰好如此,我最近爲某人寫了一個例子。

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

肉是在這裏,有消息和評論與好友替換郵編:

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) 
    } 
} 
+0

謝謝!效果很好。 – robzolkos

+0

@EveFreeman,你能否再次讓這個要點可用:)? –

+0

完成!對不起,我改回了我的github用戶名。 –