dqyym3667 2017-10-03 04:06
浏览 29
已采纳

使用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

  • 写回答

1条回答 默认 最新

  • douxiong2999 2017-10-03 04:15
    关注

    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"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类