I'm trying to learn go and I want to create a many to many relationship between a post and a tag. A tag can belong to many posts and a post can have many tags. I am using the standard library using the mysql drive (github.com/go-sql-driver/mysql)
Here's my code:
post.go
package main
type post struct {
ID int `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
Tags: Tag `json:"tags"`
}
tag.go
package main
type tag struct {
ID int `json:"id"`
Name string `json:"name"`
Posts: Post `json:"posts"`
}
Is this the correct way to structure this many to many relationship?
Cheers
Here are a couple of modifications to consider:
post
vs. Post
for example)[]*Post
and []*Tag
for example), but popular ORM libraries don't strictly need that (for example gorm: http://jinzhu.me/gorm/associations.html#many-to-many).Example code:
type Post struct {
ID int `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
Tags []Tag `json:"tags"`
}
type Tag struct {
ID int `json:"id"`
Name string `json:"name"`
Posts []Post `json:"posts"`
}