Files
go_blog/models/options.go

43 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package models
import "gorm.io/gorm"
// Option 对应 typecho_options 数据表
// 用于存储系统配置项
type Option struct {
Name string `gorm:"column:name;type:varchar(32);primaryKey"` // 配置名称(主键)
Value string `gorm:"column:value;type:text"` // 配置值
User int `gorm:"column:user;type:int;default:0"` // 用户ID0表示全局配置
}
// TableName 指定表名
func (Option) TableName() string {
return "typecho_options"
}
// GetOptionValue 根据name和user获取配置值
// 返回配置值错误无记录时返回gorm.ErrRecordNotFound
func GetOptionValue(db *gorm.DB, name string, user int) (string, error) {
var option Option
result := db.Where("name = ? AND user = ?", name, user).First(&option)
if result.Error != nil {
return "", result.Error // 可能返回gorm.ErrRecordNotFound或其他数据库错误
}
return option.Value, nil
}
// SetOptionValue 根据name和user设置配置值存在则更新不存在则新增
func SetOptionValue(db *gorm.DB, name string, user int, value string) error {
// 构造要更新/插入的配置项
option := Option{
Name: name,
User: user,
Value: value,
}
// 使用GORM的Save方法自动判断是否存在存在则更新不存在则插入
result := db.Save(&option)
return result.Error
}