package entities import ( "time" "github.com/google/uuid" "gorm.io/gorm" ) // Category 文章分类实体 // 用于对文章进行分类管理,支持层级结构和排序 type Category struct { // 基础标识 ID string `gorm:"primaryKey;type:varchar(36)" json:"id" comment:"分类唯一标识"` Name string `gorm:"type:varchar(100);not null" json:"name" comment:"分类名称"` Description string `gorm:"type:text" json:"description" comment:"分类描述"` SortOrder int `gorm:"default:0" json:"sort_order" comment:"排序"` // 时间戳字段 CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at" comment:"创建时间"` UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at" comment:"更新时间"` DeletedAt gorm.DeletedAt `gorm:"index" json:"-" comment:"软删除时间"` // 关联关系 Articles []Article `gorm:"foreignKey:CategoryID" json:"articles,omitempty" comment:"分类下的文章"` // 领域事件 (不持久化) domainEvents []interface{} `gorm:"-" json:"-"` } // TableName 指定表名 func (Category) TableName() string { return "article_categories" } // BeforeCreate GORM钩子:创建前自动生成UUID func (c *Category) BeforeCreate(tx *gorm.DB) error { if c.ID == "" { c.ID = uuid.New().String() } return nil } // 实现 Entity 接口 - 提供统一的实体管理接口 // GetID 获取实体唯一标识 func (c *Category) GetID() string { return c.ID } // GetCreatedAt 获取创建时间 func (c *Category) GetCreatedAt() time.Time { return c.CreatedAt } // GetUpdatedAt 获取更新时间 func (c *Category) GetUpdatedAt() time.Time { return c.UpdatedAt } // Validate 验证分类信息 // 检查分类必填字段是否完整,确保数据的有效性 func (c *Category) Validate() error { if c.Name == "" { return NewValidationError("分类名称不能为空") } // 验证名称长度 if len(c.Name) > 100 { return NewValidationError("分类名称不能超过100个字符") } return nil } // SetSortOrder 设置排序 func (c *Category) SetSortOrder(order int) { c.SortOrder = order }