示例
以下是一个完整的Gorm模型定义示例:
代码语言:javascript复制package models
import (
"gorm.io/gorm"
)
type User struct {
gorm.Model
Name string `gorm:"uniqueIndex"`
Age int `gorm:"index"`
Gender string `gorm:"size:255;not null"`
CreatedAt time.Time `gorm:"autoCreateTime"`
UpdatedAt time.Time `gorm:"autoUpdateTime"`
DeletedAt *time.Time `gorm:"index"`
Articles []Article
Roles []Role `gorm:"many2many:user_roles;"`
}
type Article struct {
gorm.Model
Title string
Content string
UserID uint
User User `gorm:"foreignKey:UserID"`
Comments []Comment
Categories []Category `gorm:"many2many:article_categories;"`
}
type Comment struct {
gorm.Model
Content string
ArticleID uint
Article Article `gorm:"foreignKey:ArticleID"`
}
type Category struct {
gorm.Model
Name string `gorm:"uniqueIndex"`
Articles []Article `gorm:"many2many:article_categories;"`
}
type Role struct {
gorm.Model
Name string
Users []User `gorm:"many2many:user_roles;"`
}
在上述代码中,我们定义了四个模型:User、Article、Comment和Category,以及一个Role模型,用于演示BelongsTo、HasOne、HasMany和ManyToMany关系的使用。其中,User模型与Article模型使用了HasMany关系,Article模型与Comment模型使用了HasMany关系,Article模型与Category模型使用了ManyToMany关系,User模型与Role模型使用了ManyToMany关系。