Files
nl-blogs/server/models/category.go
2026-06-26 17:00:02 +08:00

57 lines
1.4 KiB
Go

package models
import (
"time"
"gorm.io/gorm"
)
// Category 分类模型
type Category struct {
ID uint `json:"id" gorm:"primaryKey;column:id"`
Name string `json:"name" gorm:"column:name"`
Slug string `json:"slug" gorm:"column:slug;uniqueIndex"`
Description string `json:"description" gorm:"column:description;type:text"`
SortOrder uint `json:"sortOrder" gorm:"column:sort_order;default:0"`
CreatedAt int64 `json:"createdAt" gorm:"column:created_at"`
UpdatedAt int64 `json:"updatedAt" gorm:"column:updated_at"`
DeletedAt int64 `json:"deletedAt" gorm:"column:deleted_at;default:0"`
}
// TableName 指定表名
func (Category) TableName() string {
return "categories"
}
// BeforeCreate 创建前钩子
func (c *Category) BeforeCreate(tx *gorm.DB) error {
now := time.Now().Unix()
if c.CreatedAt == 0 {
c.CreatedAt = now
}
if c.UpdatedAt == 0 {
c.UpdatedAt = now
}
if c.DeletedAt == 0 {
c.DeletedAt = 0
}
return nil
}
// BeforeUpdate 更新前钩子
func (c *Category) BeforeUpdate(tx *gorm.DB) error {
c.UpdatedAt = time.Now().Unix()
return nil
}
// CategoryResponse 分类 API 响应
type CategoryResponse struct {
ID uint `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
Description string `json:"description"`
SortOrder uint `json:"sortOrder"`
CreatedAt string `json:"createdAt"`
UpdatedAt string `json:"updatedAt"`
}