approveflow/app/base/extension.go

74 lines
3.0 KiB
Go
Raw Normal View History

2024-11-14 17:02:41 +08:00
package base
import "strings"
// BaseExtensionField 结构体,类似于 Java 中的 BaseExtensionField
type BaseExtensionField struct {
ID int64 `gorm:"primaryKey;autoIncrement" json:"id"` // 主键ID
TableName string `gorm:"type:varchar(255);not null" json:"table_name"`
FieldName string `gorm:"type:varchar(255);not null" json:"field_name"`
Extension string `gorm:"type:varchar(255)" json:"extension"`
FieldValue string `gorm:"type:varchar(255)" json:"field_value"`
OwnerID int64 `gorm:"index" json:"owner_id"` // 外键关联到主结构体
}
// ExtensionFieldManageable 接口定义获取扩展字段的方法
type ExtensionFieldManageable interface {
GetExtensionFields() []BaseExtensionField
GetExtensionFieldsByFieldName(fieldName string) []BaseExtensionField
GetExtensionFieldsByFieldNameAndExtension(fieldName, extension string) []BaseExtensionField
GetExtensionFieldValueByFieldName(fieldName string) *string
GetExtensionFieldValueByFieldNameAndExtension(fieldName, extension string) *string
}
// DefaultExtensionFieldManager 用于实现 ExtensionFieldManageable 的默认行为
type DefaultExtensionFieldManager struct {
ExtensionFields []BaseExtensionField `gorm:"foreignKey:OwnerID;references:ID" json:"extensions"` // 扩展字段列表
ExtensionFieldManageable `gorm:"-"`
}
// GetExtensionFields 实现了 ExtensionFieldManageable 接口的 GetExtensionFields 方法
func (m *DefaultExtensionFieldManager) GetExtensionFields() []BaseExtensionField {
return m.ExtensionFields
}
// GetExtensionFieldsByFieldName 过滤指定字段名的扩展字段
func (m *DefaultExtensionFieldManager) GetExtensionFieldsByFieldName(fieldName string) []BaseExtensionField {
var result []BaseExtensionField
for _, field := range m.ExtensionFields {
if strings.EqualFold(field.FieldName, fieldName) {
result = append(result, field)
}
}
return result
}
// GetExtensionFieldsByFieldNameAndExtension 过滤指定字段名和扩展名的扩展字段
func (m *DefaultExtensionFieldManager) GetExtensionFieldsByFieldNameAndExtension(fieldName, extension string) []BaseExtensionField {
var result []BaseExtensionField
for _, field := range m.GetExtensionFieldsByFieldName(fieldName) {
if strings.EqualFold(field.Extension, extension) {
result = append(result, field)
}
}
return result
}
// GetExtensionFieldValueByFieldName 返回指定字段名的第一个扩展字段值
func (m *DefaultExtensionFieldManager) GetExtensionFieldValueByFieldName(fieldName string) string {
fields := m.GetExtensionFieldsByFieldName(fieldName)
if len(fields) > 0 {
return fields[0].FieldValue
}
return ""
}
// GetExtensionFieldValueByFieldNameAndExtension 返回指定字段名和扩展名的第一个扩展字段值
func (m *DefaultExtensionFieldManager) GetExtensionFieldValueByFieldNameAndExtension(fieldName, extension string) string {
fields := m.GetExtensionFieldsByFieldNameAndExtension(fieldName, extension)
if len(fields) > 0 {
return fields[0].FieldValue
}
return ""
}