To achieve the function.
Article belongs to a category.
Articles have multiple labels
Four related tables Table in a database created in advance. No foreign key relationships
- article Table
- tag table.
- article_tag 表
- category table
//文章表
type Article struct {
Id int `json:"id"`
Title string `json:"title"`
CategoryId int `json:"category_id"`
Category Category `json:"category";gorm:"foreignkey:CategoryID"`//指定关联外键
Tag []Tag `gorm:"many2many:article_tag" json:"tag"`//多对多关系.
//article_tag表默认article_id字段对应article表id.tag_id字段对应tag表id
//可以把对应sql日志打印出来,便于调试
}
//文章_标签中间表
type ArticleTag struct {
Id int `json:"id" `
ArticleId string `json:"article_id"`
TagId string `json:"tag_id"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
//标签表
type Tag struct {
Id int `json:"id" `
TagName string `json:"tag_name"`
}
//分类表
type Category struct {
ID int `json:"id"`
CategoryName string `json:"category_name"`
Status int `json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
//远程一对多.一对一
func (a *Article) ListArticle(title string) (Article, error) {
query := database.GormPool
var article Article
query.Where("title like ?", "%"+title+"%").First(&article)
fmt.Println(article)
err := query.Model(&article).
Related(&article.Category).
Related(&article.Tag, "tag").
Find(&article).Error
if err != nil && err != gorm.ErrRecordNotFound {
return article, nil
}
return article, err
}
The results are shown: a classification, a plurality of tags
used Related methods require good Article first query,
and then to find the definition of Category Article according to the CategoryID specified,
find a tag, label directly received Tag sections defined: Then write table corresponding to the gorm relationship: "many2many: article_tag"
func (a *Article) ListArticle(title string) (articles []Article, err error) {
query := database.GormPool
err = query.Model(articles).
Where("title like ?", "%"+title+"%").
Preload("Category").
Preload("Tag").Find(&articles).Error
if err != nil && err != gorm.ErrRecordNotFound {
return
}
return
}
Preload method using direct mode as above will be able to find, as a result of the check out
There is a problem, you can add micro letter: cfun666, go into the language learning exchange group