go17/book/model/book.go
2024-11-23 12:11:44 +08:00

56 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 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"`
}
// 怎么校验 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"
}