61 lines
1.3 KiB
Go
61 lines
1.3 KiB
Go
package model
|
||
|
||
import (
|
||
"fmt"
|
||
|
||
"github.com/go-playground/validator/v10"
|
||
"github.com/infraboard/mcube/v2/tools/pretty"
|
||
)
|
||
|
||
var (
|
||
v = validator.New()
|
||
)
|
||
|
||
// Book 结构体定义
|
||
type Book struct {
|
||
// grom:"column:isbn;", 具体文档: https://gorm.io/docs/models.html#Fields-Tags
|
||
IsBN uint `json:"isbn" gorm:"primaryKey;column:isbn"`
|
||
BookSpec
|
||
}
|
||
|
||
// ret, err := json.MarshalIndent(e, "", jsonIndent)
|
||
//
|
||
// if err != nil {
|
||
// return fmt.Sprintf("%+v", e)
|
||
// }
|
||
//
|
||
// return string(ret)
|
||
func (b *Book) String() string {
|
||
// 我提炼出来功能代码工具
|
||
return pretty.ToJSON(b)
|
||
}
|
||
|
||
type BookSpec struct {
|
||
Title string `json:"title" gorm:"column:title;type:varchar(200)" validate:"required"`
|
||
Author string `json:"author" gorm:"column:author;type:varchar(200);index" validate:"required"`
|
||
Price float64 `json:"price" gorm:"column:price" validate:"required"`
|
||
// bool false
|
||
// nil 是零值, false
|
||
IsSale *bool `json:"is_sale" gorm:"column:is_sale"`
|
||
}
|
||
|
||
// %s
|
||
func (s *BookSpec) String() string {
|
||
return pretty.ToJSON(s)
|
||
}
|
||
|
||
// 怎么校验 struct 参数
|
||
func (r *BookSpec) Validate() error {
|
||
if r.Author == "" {
|
||
return fmt.Errorf("author 不能为空")
|
||
}
|
||
|
||
// 通用的校验逻辑,比如是否为空,可以考虑使用validate包
|
||
return v.Struct(r)
|
||
}
|
||
|
||
// 定义该对象映射到数据里 表的名称
|
||
func (t *Book) TableName() string {
|
||
return "books"
|
||
}
|