go17/book/model/book.go

56 lines
1.3 KiB
Go
Raw Normal View History

2024-11-23 10:55:52 +08:00
package model
2024-11-23 12:11:44 +08:00
import (
"fmt"
"github.com/go-playground/validator/v10"
"github.com/infraboard/mcube/v2/tools/pretty"
)
var (
v = validator.New()
)
2024-11-23 10:55:52 +08:00
// Book 结构体定义
type Book struct {
// grom:"column:isbn;", 具体文档: https://gorm.io/docs/models.html#Fields-Tags
IsBN uint `json:"isbn" gorm:"primaryKey;column:isbn"`
BookSpec
}
2024-11-23 12:11:44 +08:00
// 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)
}
2024-11-23 10:55:52 +08:00
type BookSpec struct {
2024-11-23 12:11:44 +08:00
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"`
2024-11-23 10:55:52 +08:00
// bool false
// nil 是零值, false
IsSale *bool `json:"is_sale" gorm:"column:is_sale"`
}
2024-11-23 12:11:44 +08:00
// 怎么校验 struct 参数
func (r *BookSpec) Validate() error {
if r.Author == "" {
return fmt.Errorf("author 不能为空")
}
// 通用的校验逻辑比如是否为空可以考虑使用validate包
return v.Struct(r)
}
2024-11-23 10:55:52 +08:00
// 定义该对象映射到数据里 表的名称
func (t *Book) TableName() string {
return "books"
}