Files
nl-blogs/server/models/snippet.go
2026-01-19 13:53:32 +08:00

55 lines
1.3 KiB
Go

package models
import (
"time"
"gorm.io/gorm"
)
// Snippet 代码片段模型
type Snippet struct {
ID string `json:"id" gorm:"primaryKey;column:id"`
Title string `json:"title" gorm:"column:title"`
Code string `json:"code" gorm:"column:code;type:text"`
Type string `json:"type" gorm:"column:type"`
Description string `json:"description" gorm:"column:description;type:text"`
ViewCount uint `json:"viewCount" gorm:"column:view_count;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 (Snippet) TableName() string {
return "snippets"
}
// BeforeCreate 创建前钩子
func (s *Snippet) BeforeCreate(tx *gorm.DB) error {
now := time.Now().Unix()
if s.CreatedAt == 0 {
s.CreatedAt = now
}
if s.UpdatedAt == 0 {
s.UpdatedAt = now
}
if s.DeletedAt == 0 {
s.DeletedAt = 0
}
return nil
}
// BeforeUpdate 更新前钩子
func (s *Snippet) BeforeUpdate(tx *gorm.DB) error {
s.UpdatedAt = time.Now().Unix()
return nil
}
// SnippetResponse 代码片段响应模型
type SnippetResponse struct {
ID string `json:"id"`
Title string `json:"title"`
Code string `json:"code"`
Type string `json:"type"`
}