This commit is contained in:
2026-06-21 19:29:42 +08:00
parent 4f6c24cc49
commit a84982e1f5
8 changed files with 320 additions and 6 deletions
+38
View File
@@ -0,0 +1,38 @@
package models
import (
"time"
"gorm.io/gorm"
)
// Article status constants.
const (
ArticleDraft = 0 // 草稿
ArticlePublished = 1 // 已发布
ArticleArchived = 2 // 已归档
)
// Article represents a blog post.
type Article struct {
ID uint `gorm:"primarykey" json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"uniqueIndex:idx_slug_deleted_at" json:"deleted_at"`
AuthorID uint `gorm:"not null;index" json:"author_id"`
Title string `gorm:"not null;size:255" json:"title"`
Summary string `gorm:"size:512" json:"summary"`
Content string `gorm:"type:text;not null" json:"content"`
Cover string `gorm:"size:512" json:"cover"`
Status int `gorm:"default:0;index" json:"status"`
IsTop bool `gorm:"default:false" json:"is_top"`
ViewCount int `gorm:"default:0" json:"view_count"`
Slug string `gorm:"uniqueIndex:idx_slug_deleted_at;size:255" json:"slug"`
PublishedAt *time.Time `gorm:"index" json:"published_at"`
Author User `gorm:"foreignKey:AuthorID" json:"-"`
}
// TableName overrides the default GORM table name.
func (Article) TableName() string {
return "articles"
}
+2 -2
View File
@@ -44,8 +44,8 @@ func InitDB(cfg *config.Config) *gorm.DB {
log.Fatalf("Failed to connect to database: %v", err)
}
// Auto-migrate the User table (idempotent).
if err := db.AutoMigrate(&User{}); err != nil {
// Auto-migrate tables (idempotent).
if err := db.AutoMigrate(&User{}, &Article{}); err != nil {
log.Fatalf("Failed to auto-migrate database: %v", err)
}
+1
View File
@@ -33,6 +33,7 @@ type User struct {
Email string `gorm:"size:255" json:"email"`
Status int `gorm:"default:1" json:"status"`
Role string `gorm:"size:32;default:author" json:"role"`
Articles []Article `gorm:"foreignKey:AuthorID" json:"-"`
}
// SetPassword hashes the plain-text password with bcrypt and stores it.