go语言的gin框架+mysql做web开发,模型之间的关联问题,下面有个示例:
package model
import "time"
// Article 文章
type Article struct {
ID uint `gorm:"primary_key" json:"id"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt *time.Time `sql:"index" json:"deletedAt"`
Name string `json:"name"`
BrowseCount uint `json:"browseCount"`
CommentCount uint `json:"commentCount"`
CollectCount uint `json:"collectCount"`
Status int `json:"status"`
Content string `json:"content"`
HTMLContent string `json:"htmlContent"`
ContentType int `json:"contentType"`
Categories []Category `gorm:"many2many:article_category;ForeignKey:ID;AssociationForeignKey:ID" json:"categories"`
Comments []Comment `gorm:"ForeignKey:SourceID" json:"comments"`
UserID uint `json:"userID"`
User User `json:"user"`
LastUserID uint `json:"lastUserID"` //最后一个回复文章的人
LastUser User `json:"lastUser"`
LastCommentAt *time.Time `json:"lastCommentAt"`
}
问题:
1、User和Article是一对多的关系,不太明白上面的代码为什么要把User
和UserID
都写上,只写UserID
不就行了吗?
2、这里写上User
,意思是articles
表有一个user
字段来保存这个user的信息?
补充:
建表的sql代码又没有写user字段,那上面Article结构体为什么要写上User?
@cherrylee 贴出来的代码是service & model 混合的数据结构。你想要的应该是这样的吧?
我个人推荐解耦合的写法,之间可以通过一个load函数来转换model到service解构。为此我还写了一个工具来完成这部分工作。。。
yeqown.github.io/Golang适用的DTO工具,希望对你有帮助。