You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
1.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package gormExample
import (
"gorm.io/gorm"
"gorm.io/gorm/clause"
"log"
"time"
)
type Content struct {
gorm.Model
Subject string
Likes uint `gorm:""`
Views uint `gorm:""`
//Likes uint `gorm:"default:99"`
//Views *uint `gorm:"default:99"`
PublishTime *time.Time
// 不需要迁移
// 禁用写操作
Sv string `gorm:"-:migration;<-:false"`
// 作者ID
AuthorID uint
}
// Author模型
type Author struct {
gorm.Model
Status int
Name string
Email string
}
type ContentStrPK struct {
ID string `gorm:"primaryKey"`
Subject string
Likes uint
Views uint
PublishTime *time.Time
}
const (
defaultViews = 99
defaultLikes = 99
)
func NewContent() Content {
return Content{
Likes: defaultLikes,
Views: defaultViews,
}
}
// Hook
func (c *Content) BeforeCreate(db *gorm.DB) error {
// 业务
if c.PublishTime == nil {
now := time.Now()
c.PublishTime = &now
}
// 配置
db.Statement.AddClause(clause.OnConflict{UpdateAll: true})
log.Println("content before create hook")
return nil
}
func (c *Content) AfterCreate(db *gorm.DB) error {
//return errors.New("custom error")
return nil
}
func (c *Content) AfterFind(db *gorm.DB) error {
if c.AuthorID == 0 {
c.AuthorID = 1 // 1 假定的默认作者
}
return nil
}