Search code examples
mysqlgomany-to-many

model structs for many to many relationship using std


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


Solution

  • Here are a couple of modifications to consider:

    1. Keep your type names consistent (post vs. Post for example)
    2. I think you were going for a slice of Tags and a slice of Posts, so I updated the syntax for that.
    3. One significant question you'll need to answer; do you need/want your structures to be stored in memory with single structs for each item? If so you'll probably want to consider using slices of pointers to Tag and Post instead ([]*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"`
    }