Files
nl-blogs/server/models/snippet.go
2026-06-25 16:57:06 +08:00

61 lines
1.8 KiB
Go

package models
import (
"time"
"gorm.io/gorm"
)
// Snippet 代码片段模型
type Snippet struct {
ID uint `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
Title string `json:"title" gorm:"column:title"`
Code string `json:"code" gorm:"column:code;type:text"`
Type string `json:"type" gorm:"column:type"`
CodeTypeID uint `json:"codeTypeId" gorm:"column:code_type_id"`
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 uint `json:"id"`
Title string `json:"title"`
Code string `json:"code"`
Type string `json:"type"`
CodeTypeID uint `json:"codeTypeId,omitempty"`
CodeType *CodeTypeResponse `json:"codeType,omitempty"`
Description string `json:"description,omitempty"`
ViewCount uint `json:"viewCount,omitempty"`
Posts []PostBrief `json:"posts,omitempty"`
}