feat(gormtypes): go-hua/datatypes 迁入并更名 gormtypes(GORM/JSON 双向类型)
- 原包名与 gorm.io/datatypes 易混淆, 实为 GORM Value/Scanner + JSON 序列化 类型族, 更名 gormtypes; 8 种类型与测试同步迁移 - 附 examples/gormtypes 例程与包 README
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
# gormtypes
|
||||
|
||||
GORM/JSON 双向转换类型:写库时序列化为 JSON 字符串,读库时反序列化还原,
|
||||
API 输出按前端需要的格式直出。含 BoolSlice、IntSlice、Int32Slice、Int64Slice、
|
||||
UInt64Slice、Float64Slice、StringSlice、StringMap 八种类型。
|
||||
|
||||
> 迁移自 go-hua/datatypes 并更名:原包名与 `gorm.io/datatypes` 官方包易混淆,
|
||||
> 且该包专为 GORM 服务,故更名 `gormtypes`。
|
||||
|
||||
## 用法
|
||||
|
||||
```go
|
||||
import "git.zeroonesoft.cn/golib/zogo/gormtypes"
|
||||
|
||||
type Server struct {
|
||||
ID int64 `json:"id"`
|
||||
Tags gormtypes.StringSlice `gorm:"type:varchar(512)" json:"tags"` // 库里存 `["a","b"]`
|
||||
Flags gormtypes.BoolSlice `gorm:"type:varchar(256)" json:"flags"` // 库里存 `[true,false]`
|
||||
Extra gormtypes.StringMap `gorm:"type:varchar(1024)" json:"extra"`
|
||||
}
|
||||
|
||||
// 每种类型附辅助方法(以 BoolSlice 为例)
|
||||
s := gormtypes.BoolSlice{true, false, true}
|
||||
s.AnyTrue() // true
|
||||
s.AllTrue() // false
|
||||
s.CountTrue() // 2
|
||||
s.ToSlice() // []bool
|
||||
```
|
||||
|
||||
完整可运行例程:[examples/gormtypes/main.go](../examples/gormtypes/main.go)
|
||||
|
||||
## 注意
|
||||
|
||||
- 数据库列建议 `varchar`/`text`(存 JSON 字符串),不要用 JSON 列类型。
|
||||
- 消费方 API 输出时 `MarshalJSON` 直出原生数组/对象,前端无感知。
|
||||
- 迁移自 go-hua 的消费方:import 路径与包名 `datatypes` → `gormtypes`,类型名不变。
|
||||
Reference in New Issue
Block a user