项目地址:https://gitee.com/illlloooovvvvcode/daily-blog
主要任务:数据库表设计
数据库表设计
1. ER图
目前,主体上只有四个模块,设计五张表
- posts 文章表
- tags 标签表
- post_tags 文章-标签表
- categorys 分类表
- comments 评论表
2.创建model
位置:/daily-blog/model
2.1 post
type Post struct {
gorm.Model
PostId string `gorm:"post_id;type:CHAR(32) NOT NULL;comment:post唯一id"` // uuid生成
Title string `gorm:"column:title; type:VARCHAR(255) NOT NULL;comment:标题"`
Desc string `gorm:"column:desc;type:VARCHAR(1024) NOT NULL; comment:描述"`
Content string `gorm:"column:content;type:TEXT NOT NULL; comment:内容"`
Author string `gorm:"column:author;type:VARCHAR(32) NOT NULL;comment:作者"`
CategoryId int64 `gorm:"column:category_id;type:CHAR(32) NOT NULL; comment:类别唯一id"`
CategoryName string `gorm:"column:category; type:VARCHAR(32) NOT NULL;comment:分类名"`
Love int `gorm:"column:love; comment:点赞次数"`
Watch int `gorm:"column:watch; comment:浏览次数"`
}
2.2 tag
type Tag struct {
gorm.Model
TagId string `gorm:"column:tag_id;type:CHAR(32) NOT NULL; comment:tag唯一id"`
TagName string `gorm:"column:tag_name;type:VARCHAR(32) NOT NULL; comment:标签名"`
}
2.3 post_tags
type PostTag struct {
gorm.Model
PostId string `gorm:"column:post_id;type:CHAR(32) NOT NULL; comment:post唯一id"`
TagId string `gorm:"column:tag_id;type:CHAR(32) NOT NULL; comment:tag唯一id"`
TagName string `gorm:"column:tag_name;type:VARCHAR(32) NOT NULL;comment:标签名"`
}
2.4 comment
type Comment struct {
gorm.Model
CommentId string `gorm:"column:comment_id;type:CHAR(32) NOT NULL; comment:评论id"`
Author string `gorm:"column:author;type:VARCHAR(32) NOT NULL; comment:评论人"`
Content string `gorm:"column:content;type:VARCHAR(1024) NOT NULL; comment:评论内容"`
PostId string `gorm:"column:post_id;type:CHAR(32) NOT NULL; comment:评论文章的id"`
}
2.5 category
type Category struct {
gorm.Model
CategoryId string `gorm:"column:category_id;type:CHAR(32) NOT NULL;comment:category唯一id"`
Name string `gorm:"column:name;type:VARCHAR(32) NOT NULL;comment:分类名"`
}
2.6 指定表名
每一个model可以指定TableName·方法指定自动迁移时的表名
例如:
func (PostTag) TableName() string {
return "post_tags"
}
3. 迁移表结构
/daily-blog/global/init-db.go 中
func initTables(db *gorm.DB) {
db.AutoMigrate(&model.Post{})
db.AutoMigrate(&model.Tag{})
db.AutoMigrate(&model.PostTag{})
db.AutoMigrate(&model.Category{})
db.AutoMigrate(&model.Comment{})
}